/**
 * <b>The Object of CloudHomeScreen Class</b>
 */
var chs,		// global variable, but cannot be deleted by 'delete' operator
	chsConstants,
	statusbar,
	pu;		// PerformanceUtil instance variable

/**
 * invoke server sync by push notification
 */
window.addEventListener('message', function(e) {
//	chs.getEventHandler().showStatusBar("Push Message. Synchronizing...");
//	chs.getSyncManager().server_sync(function(message) {
//		chs.getEventHandler().hideStatusBar();
//		chs.getEventHandler().onDBDataChanged();
//	});
	location.reload();
	
	// send return message to Quick Panel
	var customEvent = document.createEvent('MessageEvent'),
		data = '{"WebPageMessage":[{"url":http://cloudphone.dyndns.org/aphone/cloudhome}]}';	// temporary
	customEvent.initMessageEvent("onWebPageEvent", true, true, data, null, null, null, null);
	window.dispatchEvent(customEvent);
}, false);

/**
 * @function
 */
function pageLoaded() {
	var cloudHomeScreen;
	
	console.log((new Date()).getTime());
	
	/** Start loading CHS */
	chsConstants = new ChsConstants();				// Constant variables for CHS
	pu = new PerformanceUtil("CHS", "onload");		// PerformanceUtil
	
	pu.startMilestone("create, instance, CloudHomeScreen");
	chs = new CloudHomeScreen();		// Make CloudHomeScreen Object
	pu.finishMilestone("create, instance, CloudHomeScreen");
	
	cloudHomeScreen = chs;
	cloudHomeScreen.initAccountManager();		// Initialize AccountManager
	
	cloudHomeScreen.getEventHandler().showStatusBar("Load CHS using localStorage data");
	var isNotLoaded = cloudHomeScreen.getDataFromLocalStorage();		// CHS loading using local storage data
	if (isNotLoaded) {
		cloudHomeScreen.getDataFromDB(isNotLoaded);
	} else {
		/*jQuery(window).load(function() {
			cloudHomeScreen.getDataFromDB(isNotLoaded);
		});*/
		setTimeout(function() {
			cloudHomeScreen.getDataFromDB(isNotLoaded);		// setTimeout �놁뼱��愿쒖갖�쇰젮��...
		}, 500);
	}
}


/** ChsConstants */
var ChsConstants = function() {
	this.initialize();
};
ChsConstants.prototype.initialize = function() {
	this.syncManagerServerSynced = false;
	this.dataSourceCount = 4;		// chs_segment, chs_layout, chs_segment_option, webclip
	this.isCloudPhone = isCloudPhone();
	this.isMobile = isMobile();
	this.tapReplaceEvent = (this.isMobile ? "touchend touchcancel" : "mouseup");
	this.workerExist = (window.Worker ? true : false);
};


/**
 * CloudHomeScreen Class
 * @class CloudHomeScreen
 * @constructor
 * @author skamic
 */
var CloudHomeScreen = function() {
	this.initialize();
};

/**
 * @lends CloudHomeScreen.prototype
 */
CloudHomeScreen.prototype = {
	initialize : function() {
		// Initialize Managers.
		this.homeManager = new HomeManager(this);
		this.segmentManager = new SegmentManager(this);
		this.webclipManager = new WebclipManager(this);
		this.homeEventHandler = new CHSEventHandler(this);
		
		this.configHashChangeEvent();
	},
	
	/**
	 * returns HomeManager object
	 * @function getHomeManager()
	 * @param none
	 * @returns HomeManager this.homeManager
	 */
	getHomeManager : function() {
		return this.homeManager;
	},

	/**
	 * returns SegmentManager object
	 * @function
	 * @returns SegmentManager this.segmentManager
	 */
	getSegmentManager : function() {
		return this.segmentManager;
	},

	/**
	 * returns WebclipManager object
	 * @function
	 * @returns WebclipManager this.webclipManager
	 */
	getWebclipManager : function() {
		return this.webclipManager;
	},

	/**
	 * returns CHSEventHandler object
	 * @function
	 * @returns CHSEventHandler this.homeEventHandler
	 */
	getEventHandler : function() {
		return this.homeEventHandler;
	},
	
	/**
	 * returns SyncManager object
	 * @function
	 * @returns SyncManager this.syncManager
	 */
	getSyncManager : function() {
		return this.syncManager;
	},
	
	/**
	 * returns AccountManager object
	 * @function
	 * @returns AccountManager this.accountManager
	 */
	getAccountManager : function() {
		return this.accountManager;
	},
	
	/**
	 * returns SNSManager object
	 * @function
	 * @returns SNSManager this.snsManager
	 */
	getSnsManager : function() {
		return this.snsManager;
	},

	/**
	 * initialize AccountManager instance
	 * @function
	 * @param none
	 * @return none
	 */
	initAccountManager : function() {
		var cloudHomeScreen = this;
		
		pu.startMilestone("create, instance, SNSManager");
		this.snsManager = new SNSManager();		// Create SNSManager
		pu.finishMilestone("create, instance, SNSManager");
		
		pu.startMilestone("create, instance, AccountManager");
		this.accountManager = new AccountManager(function() {
			pu.finishMilestone("initialize, AccountManager");
			
			pu.startMilestone("initialize, SNSManager");
			var accessTokenList = cloudHomeScreen.getAccountManager().getAccessTokenList();
			for (var domain in accessTokenList) {
				if (accessTokenList.hasOwnProperty(domain)) {
					cloudHomeScreen.getSnsManager().addManager(domain, accessTokenList[domain]);
				}
			}
			pu.finishMilestone("initialize, SNSManager");
		}, function(error) {
			cloudHomeScreen.getCloudHomEventHandler().showErrorMessage(error);
			pu.finishMilestone("initialize, AccountManager");
		});		// Create AccountManager
		pu.finishMilestone("create, instance, AccountManager");
		
		pu.startMilestone("initialize, AccountManager");
		this.accountManager.init();		// Initialize AccountManager
	},
	
	/**
	 * initialize SyncManager instance
	 * @function initSyncManager()
	 * @param none
	 * @return none
	 */
	initSyncManager : function() {
		var cloudHomeScreen = this,
			homeEventHandler = this.getEventHandler(),
			token = getCookie("tokenval");
		
		pu.startMilestone("create, instance, SyncManager");
		this.syncManager = new SyncManager(token, "chs");		// Create SyncManager
		pu.finishMilestone("create, instance, SyncManager");
		
		pu.startMilestone("initialize, SyncManager");
		this.syncManager.init(function(key) {
			pu.finishMilestone("initialize, SyncManager");
			
			chsConstants.syncManagerServerSynced = true;
			homeEventHandler.showStatusBar("SyncManager is created. Start synchronizing.");
			homeEventHandler.onTableCreated();
		}, function(message) {
			pu.finishMilestone("initialize, SyncManager");
			
			chsConstants.syncManagerServerSynced = true;
			homeEventHandler.showErrorMessage(message);
			homeEventHandler.hideStatusBar();
		});		// Initialize SyncManager
		
		/** exception handling : when IndexedDB sends no callback... */
		setTimeout(function() {
			if (chsConstants.syncManagerServerSynced === false) {
				homeEventHandler.showErrorMessage("[Fatal Error] SyncManager Server Sync Error. Indexed DB didn't return any callback.");
				homeEventHandler.hideStatusBar();
			}
		}, 10 * 1000);

		this.syncManager.onLocalDBChanged = function() {
			homeEventHandler.onDBDataChanged();
		};
	},
	
	/**
	 * get data from local storage
	 * @function
	 * @param none
	 * @return none
	 */
	getDataFromLocalStorage : function() {
		this.homeEventHandler.loadType = "cache";
		// segmentList
		pu.startMilestone("load data, chs_segment_info, local storage");
		var lsSegmentListInfo = this.homeEventHandler.getLocalStorage("segmentListInfo");
		pu.finishMilestone("load data, chs_segment_info, local storage");
		
		if (nvl(lsSegmentListInfo) != "") {
			console.log("lsSegmentListInfo : " + lsSegmentListInfo);
			this.segmentManager.setSegmentList(JSON.parse(lsSegmentListInfo));
			this.homeEventHandler.onDataLoaded("chs_segment");
		} else {
			console.warn("No CHS data in local storage.");
			this.homeEventHandler.showStatusBar("No data in localStorage");
			return true;
		}
		
		// homeManagerInfo
		pu.startMilestone("load data, chs_layout_info, local storage");
		var lsHomeManagerInfo = this.homeEventHandler.getLocalStorage("homeManagerInfo");
		pu.finishMilestone("load data, chs_layout_info, local storage");
		
		if (nvl(lsHomeManagerInfo) != "") {
			console.log("lsHomeManagerInfo : " + lsHomeManagerInfo);
			var homeManagerInfo = JSON.parse(lsHomeManagerInfo);
			this.homeManager.initialize(homeManagerInfo.homeList, homeManagerInfo.currentHomeId);
			this.segmentManager.initialize(homeManagerInfo.orders);
			this.homeEventHandler.onDataLoaded("chs_layout");
		}
		
		// webclipManagerInfo
		this.webclipManager.initialize();
		pu.startMilestone("load data, webclip, local storage");
		var lsWebclipManagerInfo = this.homeEventHandler.getLocalStorage("webclipManagerInfo");
		pu.finishMilestone("load data, webclip, local storage");
		
		if (nvl(lsWebclipManagerInfo) != "") {
			console.log("lsWebclipManagerInfo : " + lsWebclipManagerInfo);
			var webclipManagerInfo = JSON.parse(lsWebclipManagerInfo);
			for (var i=0, count=webclipManagerInfo.length ; i<count ; ++i) {
				var webclipInfo = webclipManagerInfo[i];
				this.webclipManager.setOption(webclipInfo);
			}
			this.homeEventHandler.onDataLoaded("webclip");
		}
		
		// segmentManagerInfo
		pu.startMilestone("load data, chs_segment_option, local storage");
		var lsSegmentManagerInfo = this.homeEventHandler.getLocalStorage("segmentManagerInfo");
		pu.finishMilestone("load data, chs_segment_option, local storage");
		
		if (nvl(lsSegmentManagerInfo) != "") {
			console.log("lsSegmentManagerInfo : " + lsSegmentManagerInfo);
			var segmentManagerInfo = JSON.parse(lsSegmentManagerInfo);
			this.segmentManager.setSegmentOptions(segmentManagerInfo);
			this.segmentManager.loadSegments(this.homeManager.getCurrentHomeId());
			this.homeEventHandler.onDataLoaded("chs_segment_option");
		}
		
		console.warn("---------- from local storage ----------");
		
		return false;
	},
	
	getDataFromDB : function(mustBeLoaded) {
		var cloudHomeScreen = this;
		
		this.homeEventHandler.loadType = "server";
		if (this.homeEventHandler.checkOnLine()) {
			console.warn("--- chs_segment information is required : " + mustBeLoaded + " ---");
			if (mustBeLoaded) {
				this.getSegmentInfo(function() {
					if (chsConstants.isCloudPhone) {
						this.initSyncManager();
					} else {
						this.getData();
					}
				});
			} else {
				this.getSegmentInfo();
				if (chsConstants.isCloudPhone) {
					this.initSyncManager();
				} else {
					this.getData();
				}
			}
		}
	},

	/**
	 * get data from DB
	 * <li>if 'online', then from DB</li>
	 * <li>else, then from local storage</li>
	 * @function
	 * @param none
	 * @return none
	 */
	getData : function(reload) {
		var cloudHomeScreen = this,
			homeEventHandler = this.getEventHandler();
		
		homeEventHandler.segmentLoadCount = 0;
		if (homeEventHandler.checkOnLine()) {
			if (chsConstants.isCloudPhone) {
				homeEventHandler.showStatusBar("Load CHS using Local DB.");
				this.getWebclipInfo(cloudHomeScreen, reload);
				this.getLayoutInfo(cloudHomeScreen, reload);
			} else {
				homeEventHandler.showStatusBar("Load CHS using Server DB.");
				this.getWebclipInfoFromWeb(cloudHomeScreen);
				this.getLayoutInfoFromWeb(cloudHomeScreen);
			}
		}
	},
	
	/**
	 * get chs_layout information
	 * @function
	 * @param CloudHomeScreen cloudHomeScreen (this)
	 * @return none
	 */
	getLayoutInfo : function(cloudHomeScreen, reload) {
		var homeEventHandler = cloudHomeScreen.getEventHandler(),
			valueobject = new SyncManager.CHSLayout();
		
		pu.startMilestone("load data, chs_layout, local db");
		this.syncManager.select(valueobject, function(result) {
			pu.finishMilestone("load data, chs_layout, local db");
			
//			homeEventHandler.layoutInfoLoaded = true;		// set layout load information
			var rowCount = result.rows.length;
			if (rowCount > 0) {
				for (var i=0 ; i<rowCount ; ++i) {
					var row = result.rows.item(i),
						layoutInfo = JSON.parse(row.layouts);
					
					console.log("[layoutInfo in Local DB] " + row.layouts);
					cloudHomeScreen.homeManager.initialize(layoutInfo.homeList, layoutInfo.currentHomeId);
					cloudHomeScreen.segmentManager.initialize(layoutInfo.orders);
				}
			} else {
				if (chsConstants.isCloudPhone) {
					try {
						homeEventHandler.setLocalStorage("webclip_last_synced", 0);
					} catch (e) {
						console.error(e.message);
					}
				}
				cloudHomeScreen.initData();
			}
			
			// set local storage
			homeEventHandler.setLocalStorage("homeManagerInfo", cloudHomeScreen.layoutStringify());

//			if (reload) {
//				homeEventHandler.onDataReloaded("chs_layout");
//			} else {
				homeEventHandler.onDataLoaded("chs_layout");
//			}
			
			cloudHomeScreen.getSegmentOptionInfo(cloudHomeScreen, true, reload);		// load CHS Segment Options
		}, function(message) {
			pu.finishMilestone("load data, chs_layout, local db");
			homeEventHandler.showErrorMessage(message);
			homeEventHandler.hideStatusBar();
		});
	},
	
	/**
	 * 
	 * @param cloudHomeScreen
	 */
	getLayoutInfoFromWeb : function(cloudHomeScreen) {
		var url = "/aphone/chs/layouts",
			type = "GET";
		
		pu.startMilestone("load data, chs_layout, server db");
		if (chsConstants.workerExist) {
			var data = { url : url, type : type };
			this.homeEventHandler.executeWorker("getLayoutInfo", data, function(xhr) {
				cloudHomeScreen.getLayoutInfoFromWebCallback(xhr);
			});
		} else {
			jQuery.ajax({
				url : url,
				type : type,
				complete : function(xhr) {
					if (xhr.readyState == 4) {
						cloudHomeScreen.getLayoutInfoFromWebCallback(xhr);
					}
				}
			});
		}
	},
	
	getLayoutInfoFromWebCallback : function(xhr) {
		var cloudHomeScreen = this,
			homeEventHandler = cloudHomeScreen.getEventHandler();

		pu.finishMilestone("load data, chs_layout, server db");
		
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
//					homeEventHandler.layoutInfoLoaded = true;		// set layout load information
					if (response.result.layoutInfo) {
						var layoutInfo = response.result.layoutInfo.layouts;
						
						console.log("[layoutInfo in Server DB] " + JSON.stringify(layoutInfo));
						cloudHomeScreen.homeManager.initialize(layoutInfo.homeList, layoutInfo.currentHomeId);
						cloudHomeScreen.segmentManager.initialize(layoutInfo.orders);
					} else {
						cloudHomeScreen.initData();
					}
				} else {
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
			
			// set local storage
			homeEventHandler.setLocalStorage("homeManagerInfo", cloudHomeScreen.layoutStringify());

			homeEventHandler.onDataLoaded("chs_layout");
			
			cloudHomeScreen.getSegmentOptionInfoFromWeb(cloudHomeScreen, true);		// load CHS Segment Options
		} else {
			homeEventHandler.showErrorMessage("[getLayoutInfoFromWeb] " + xhr.statusText);
			homeEventHandler.hideStatusBar();
		}
	},

	/**
	 * set default data
	 * @function
	 * @param none
	 * @return none
	 */
	initData : function() {
		var homeManager = this.getHomeManager(),
			segmentManager = this.segmentManager(),
			defaultHome = {
				homeList : [{ id : "home0", name : "Default Home #1" }],
				currentHomeId : "home0",
				homeInfo : [{ homeId : "home0", layout : ["SGMT_0000000000001"] }]
			};

		homeManager.initialize(defaultHome.homeList, defaultHome.currentHomeId);
		segmentManager.initialize(defaultHome.homeInfo);

		if (chsConstants.isCloudPhone) {
			this.insertLayoutInfo();
		}
		segmentManager.initSegmentOption(defaultHome.currentHomeId, defaultHome.homeInfo[0].layout[0]);
	},

	/**
	 * insert chs_layout information using SyncManager
	 * @function
	 * @param none
	 * @return none
	 */
	insertLayoutInfo : function() {
		var cloudHomeScreen = this,
			homeEventHandler = this.getEventHandler();
		
		homeEventHandler.showStatusBar("Insert CHS layout...");
		if (homeEventHandler.checkOnLine()) {
			if (chsConstants.isCloudPhone) {
				var valueobject = new SyncManager.CHSLayout();
				
				valueobject._layouts = this.layoutStringify();
				pu.startMilestone("insert, chs_layout, local db");
				this.syncManager.insert(valueobject, function() {
					pu.finishMilestone("insert, chs_layout, local db");
					homeEventHandler.hideStatusBar();
				}, function(message) {
					pu.finishMilestone("insert, chs_layout, local db");
					homeEventHandler.showErrorMessage(message);
					homeEventHandler.hideStatusBar();
				}, false);
			}
		} else {
			homeEventHandler.showErrorMessage("Can't insert layout information. The network is currently disconnected.");
		}
	},

	/**
	 * stringify chs_layout information for saving it in DB
	 * @function
	 * @param none
	 * @return String stringified_layout_info
	 */
	layoutStringify : function() {
		var homeList = this.homeManager.getHomeList(),
			orders = [],
			home;
		
		for (var i=0, homeCount=homeList.length ; i<homeCount ; ++i) {
			var item = {
				homeId : homeList[i].id,
				layout : this.segmentManager.getLayout(homeList[i].id)
			};
			orders.push(item);
		}

		home = {
			homeList : homeList,
			currentHomeId : this.homeManager.getCurrentHomeId(),
			orders : orders
		};

		return JSON.stringify(home);
	},

	/**
	 * get chs_segment_option information
	 * @function
	 * @param CloudHomeScreen cloudHomeScreen (this)
	 * @return none
	 */
	getSegmentOptionInfo : function(cloudHomeScreen, isCurrentHome, reload) {
		var homeEventHandler = cloudHomeScreen.getEventHandler(),
			homeManager = cloudHomeScreen.getHomeManager(),
			segmentManager = cloudHomeScreen.getSegmentManager(),
			webclipManager = cloudHomeScreen.getWebclipManager(),
			homeIds = (isCurrentHome ? [homeManager.getCurrentHomeId()] : homeManager.getHomeListExceptCurrentHomeId()),
			valueObject = new SyncManager.CHSSegmentOption();
		
		valueObject._home_id = homeIds.toString();
		
		pu.startMilestone("load data, chs_segment_option, local db");
		this.syncManager.select(valueObject, function(result) {
			pu.finishMilestone("load data, chs_segment_option, local db");
			
//			homeEventHandler.segmentOptionInfoLoaded = true;		// set segment option load information
//			var layoutLoaded = homeEventHandler.layoutInfoLoaded;	// get layout load information
			var optionInfo = [],
				rowCount = result.rows.length;
			
			if (rowCount > 0) {
				for (var i=0 ; i<rowCount ; ++i) {
					var row = result.rows.item(i),
						homeId = row.home_id,
						sgmtId = row.sgmt_id,
						options = null,
						isInitOption = false;
					
					/** deprecated segment */
					if (sgmtId.indexOf("NEWS_000") != -1) {
						continue;
					}
					
					console.log("[SegmentOptionInfo in Local DB] " + JSON.stringify(row));
					
					if (sgmtId.indexOf("wc") != -1) {
						options = webclipManager.getOption(sgmtId);
					} else {
						if (nvl(row.options) == "") {
							options = segmentManager.getInitSegmentOption(sgmtId);
							isInitOption = true;
						} else {
							options = JSON.parse(row.options);
						}
					}
					// If layout information is already loaded, then start loading this segment
//					if (layoutLoaded || !isCurrentHome) {
//						segmentManager.setSegmentOption(homeId, sgmtId, options);
//						segmentManager.loadSegment(homeId, sgmtId, options);
//					} else {
//						optionInfo.push({ homeId : homeId, sgmtId : sgmtId, options : options, isInitOption : isInitOption });
//					}
					if (isCurrentHome) {
						segmentManager.setSegmentOption(homeId, sgmtId, options);
						segmentManager.loadSegment(homeId, sgmtId, options);
					}
				}
			} else if (isCurrentHome) {
				optionInfo = segmentManager.getInitSegmentOptions(homeManager.getCurrentHomeId());
//				if (layoutLoaded) {
//					segmentManager.setSegmentOptions(optionInfo);
//					segmentManager.loadSegments(homeManager.getCurrentHomeId());
//				}
				segmentManager.setSegmentOptions(optionInfo);
				segmentManager.loadSegments(homeManager.getCurrentHomeId());
			}
			
//			if (homeEventHandler.layoutInfoLoaded || !isCurrentHome) {
//				// set local storage
//				var segmentManagerInfo = segmentManager.getSegmentManagerInfo();
//				homeEventHandler.setLocalStorage("segmentManagerInfo", JSON.stringify(segmentManagerInfo));
//			} else {
//				console.warn("CHS_LAYOUT information is not loaded yet. Wait setting segment option until layoutInfo is loaded.");
//				segmentManager.optionInfo = optionInfo;
//			}
			// set local storage
			var segmentManagerInfo = segmentManager.getSegmentManagerInfo();
			homeEventHandler.setLocalStorage("segmentManagerInfo", JSON.stringify(segmentManagerInfo));
			
			if (isCurrentHome) {
//				if (reload) {
//					homeEventHandler.onDataReloaded("chs_segment_option");
//				} else {
					homeEventHandler.onDataLoaded("chs_segment_option");
//				}
				cloudHomeScreen.getSegmentOptionInfo(cloudHomeScreen, false);
			}
		}, function(message) {
			pu.finishMilestone("load data, chs_segment_option, local db");
			cloudHomeScreen.homeEventHandler.showErrorMessage(message);
			cloudHomeScreen.homeEventHandler.hideStatusBar();
		}, "", "", "ORDER BY home_id, sgmt_id");
	},
	
	/**
	 * 
	 * @param cloudHomeScreen
	 */
	getSegmentOptionInfoFromWeb : function(cloudHomeScreen, isCurrentHome) {
		var homeEventHandler = cloudHomeScreen.getEventHandler(),
			homeManager = this.getHomeManager(),
			homeIds = (isCurrentHome ? [homeManager.getCurrentHomeId()] : homeManager.getHomeListExceptCurrentHomeId()),
			url = "/aphone/chs/segmentOptions",
			type = "GET",
			params;
		
		if (homeIds.length > 0) {
			params = "homeIds=" + encodeURIComponent(homeIds.toString());
			
			if (isCurrentHome) {
				pu.startMilestone("load data, chs_segment_option, server db");
			}
			
			if (chsConstants.workerExist) {
				var data = { url : url, type : type, data : params };
				homeEventHandler.executeWorker("getSegmentOptionInfo", data, function(xhr) {
					cloudHomeScreen.getSegmentOptionInfoFromWebCallback(xhr, isCurrentHome);
				});
			} else {
				jQuery.ajax({
					url : url,
					type : type,
					data : params,
					complete : function(xhr) {
						if (xhr.readyState == 4) {
							cloudHomeScreen.getSegmentOptionInfoFromWebCallback(xhr, isCurrentHome);
						}
					}
				});
			}
		}
	},
	
	getSegmentOptionInfoFromWebCallback : function(xhr, isCurrentHome) {
		var cloudHomeScreen = this,
			homeEventHandler = cloudHomeScreen.getEventHandler(),
			homeManager = cloudHomeScreen.getHomeManager(),
			segmentManager = cloudHomeScreen.getSegmentManager(),
			webclipManager = cloudHomeScreen.getWebclipManager();
		
		if (isCurrentHome) {
			pu.finishMilestone("load data, chs_segment_option, server db");
		}
		
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
//					homeEventHandler.segmentOptionInfoLoaded = true;		// set segment option load information
//					var layoutLoaded = homeEventHandler.layoutInfoLoaded,	// get layout load information
					var optionInfo = [],
						segmentOptions = response.result.segmentOptions;
					
					if (segmentOptions) {
						for (var i=0, optionCount=segmentOptions.length ; i<optionCount ; ++i) {
							var data = segmentOptions[i],
								homeId = data.home_id,
								sgmtId = data.sgmt_id,
								options = null,
								isInitOption = false;

							/** deprecated segment */
							if (sgmtId.indexOf("NEWS_000") != -1) {
								continue;
							}
							
							console.log("[SegmentOptionInfo in Server DB] " + JSON.stringify(data));
							
							if (sgmtId.indexOf("wc") != -1) {
								options = webclipManager.getOption(sgmtId);
							} else {
								if (nvl(data.options) == "") {
									options = segmentManager.getInitSegmentOption(sgmtId);
									isInitOption = true;
								} else {
									options = data.options;
								}
							}
							// If layout information is already loaded, then start loading this segment.
//							if (layoutLoaded || !isCurrentHome) {
//								segmentManager.setSegmentOption(homeId, sgmtId, options);
//								segmentManager.loadSegment(homeId, sgmtId, options);
//							} else {
//								optionInfo.push({ homeId : homeId, sgmtId : sgmtId, options : options, isInitOption : isInitOption });
//							}
							if (isCurrentHome) {
								segmentManager.setSegmentOption(homeId, sgmtId, options);
								segmentManager.loadSegment(homeId, sgmtId, options);
							}
						}
					} else if (isCurrentHome) {
						optionInfo = segmentManager.getInitSegmentOptions(homeManager.getCurrentHomeId());
						
//						if (layoutLoaded) {
//							segmentManager.setSegmentOptions(optionInfo);
//							segmentManager.loadSegments(homeManager.getCurrentHomeId());
//						}
						segmentManager.setSegmentOptions(optionInfo);
						segmentManager.loadSegments(homeManager.getCurrentHomeId());
					}
					
//					if (homeEventHandler.layoutInfoLoaded || !isCurrentHome) {
//						// set local storage
//						var segmentManagerInfo = segmentManager.getSegmentManagerInfo();
//						homeEventHandler.setLocalStorage("segmentManagerInfo", JSON.stringify(segmentManagerInfo));
//					} else {
//						console.warn("CHS_LAYOUT information is not loaded yet. Wait setting segment option until layoutInfo is loaded.");
//						segmentManager.optionInfo = optionInfo;
//					}
					// set local storage
					var segmentManagerInfo = segmentManager.getSegmentManagerInfo();
					homeEventHandler.setLocalStorage("segmentManagerInfo", JSON.stringify(segmentManagerInfo));
				} else {
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
			
			if (isCurrentHome) {
				homeEventHandler.onDataLoaded("chs_segment_option");
				cloudHomeScreen.getSegmentOptionInfoFromWeb(cloudHomeScreen, false);
			}
		} else {
			homeEventHandler.showErrorMessage("[getSegmentOptionInfoFromWeb] " + xhr.statusText);
			homeEventHandler.hideStatusBar();
		}
	},

	/**
	 * get webclip information
	 * @function
	 * @param CloudHomeScreen cloudHomeScreen (this)
	 * @return none
	 */
	getWebclipInfo : function(cloudHomeScreen, reload) {
		var homeEventHandler = cloudHomeScreen.getEventHandler(),
			webclipManager = cloudHomeScreen.getWebclipManager(),
			valueObject = new SyncManager.WebClip();
		
		pu.startMilestone("load data, webclip, local db");
		this.syncManager.select(valueObject, function(result) {
			pu.finishMilestone("load data, webclip, local db");
			
			webclipManager.initialize();
			for (var i=0, rowCount=result.rows.length ; i<rowCount ; ++i) {
				var row = result.rows.item(i);
				webclipManager.setOption(row);
			}
			
			// set local storage
			var webclipManagerInfo = webclipManager.getWebclipManagerInfo();
			homeEventHandler.setLocalStorage("webclipManagerInfo", JSON.stringify(webclipManagerInfo));

			if (reload) {
				homeEventHandler.onDataReloaded("webclip");
			} else {
				homeEventHandler.onDataLoaded("webclip");
			}
		}, function(message) {
			pu.finishMilestone("load data, webclip, local db");
			homeEventHandler.showErrorMessage(message);
			homeEventHandler.hideStatusBar();
		}, "", "", "order by sort_order");
	},
	
	/**
	 * 
	 * @param cloudHomeScreen
	 */
	getWebclipInfoFromWeb : function(cloudHomeScreen) {
		var url = "/aphone/chs/webclips",
			type = "GET";
		
		pu.startMilestone("load data, webclip, server db");
		if (chsConstants.workerExist) {
			var data = { url : url, type : type };
			this.homeEventHandler.executeWorker("getWebclipInfo", data, function(xhr) {
				cloudHomeScreen.getWebclipInfoFromWebCallback(xhr);
			});
		} else {
			jQuery.ajax({
				url : url,
				type : type,
				complete : function(xhr) {
					if (xhr.readyState == 4) {
						cloudHomeScreen.getWebclipInfoFromWebCallback(xhr);
					}
				}
			});
		}
	},
	
	getWebclipInfoFromWebCallback : function(xhr) {
		var homeEventHandler = this.getEventHandler(),
			webclipManager = this.getWebclipManager();
		
		pu.finishMilestone("load data, webclip, server db");
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
					var webclips = response.result.webclips;
					if (webclips) {
						webclipManager.initialize();
						for (var i=0, webclipCount=webclips.length ; i<webclipCount ; ++i) {
							webclipManager.setOption(webclips[i]);
						}
					}
				} else {
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
			
			// set local storage
			var webclipManagerInfo = webclipManager.getWebclipManagerInfo();
			homeEventHandler.setLocalStorage("webclipManagerInfo", JSON.stringify(webclipManagerInfo));

			homeEventHandler.onDataLoaded("webclip");
		} else {
			homeEventHandler.showErrorMessage("[getWebclipInfoFromWeb] " + xhr.statusText);
			homeEventHandler.hideStatusBar();
		}
	},

	/**
	 * get chs_segment information
	 * @function
	 * @param CloudHomeScreen cloudHomeScreen (this)
	 * @return none
	 */
	getSegmentInfo : function(callback) {
		var cloudHomeScreen = this,
			url = "/aphone/chs/segments",
			type = "GET";
		
		pu.startMilestone("load data, chs_segment_info, server db");
		if (chsConstants.workerExist) {
			var data = { url : url, type : type };
			this.homeEventHandler.executeWorker("getSegmentInfo", data, function(xhr) {
				cloudHomeScreen.getSegmentInfoCallback(xhr, callback);
			});
		} else {
			jQuery.ajax({
				url : url,
				type : type,
				complete : function(xhr) {
					if (xhr.readyState == 4) {
						cloudHomeScreen.getSegmentInfoCallback(xhr, callback);
					}
				}
			});
		}
	},
	
	getSegmentInfoCallback : function(xhr, callback) {
		var segmentManager = this.getSegmentManager(),
			homeEventHandler = this.getEventHandler();
		
		pu.finishMilestone("load data, chs_segment_info, server db");
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
					var segments = response.result.segments;
					if (segments) {
//							if (segmentManager.getSegmentList() == null) {
							segmentManager.setSegmentList(segments);
//							}
					} else {
						// error message
						console.error("NO SEGMENT INFORMATION.");
					}
				}
			}
			
			// set local storage
			homeEventHandler.setLocalStorage("segmentListInfo", JSON.stringify(segmentManager.getSegmentList()));

			homeEventHandler.onDataLoaded("chs_segment");
			
			if (callback && (typeof(callback) == "function")) {
				callback.call(this);
			}
		}
	},
	
	/**
	 * load Cloud Home Screen
	 * @function
	 * @param none
	 * @return none
	 */
	loadHome : function() {
		pu.startMilestone("display, home layout");
		this.initEvent();		// event, popup, buttons
		this.homeManager.loadHome();
		pu.finishMilestone("display, home layout");
	},
	
	/**
	 * initialize chs related events
	 * @function
	 * @param none
	 * @return none
	 */
	initEvent : function(isReload) {
		jQuery(".footer").show();
		this.setFooter("home");
		jQuery("#webclipWrapper").hide();
		
		if (!isReload) {
			this.initEditTopArea();
			// bind onresize event into window
			jQuery(window).bind("resize", { cloudHomeScreen : this }, this.homeEventHandler.onPageResize);
			jQuery(window).bind("orientationchange", { cloudHomeScreen : this }, this.homeEventHandler.onOrientationChange);
			jQuery(window).bind("unload", { cloudHomeScreen : this }, this.homeEventHandler.onUnload);
			this.homeEventHandler.refreshScreenWidth();		// refresh the width of screen class
			
			// set spinner
//			jQuery("#viewLoading").hide().ajaxStart(function() {
//				jQuery(this).show();
//			}).ajaxStop(function() {
//				jQuery(this).hide();
//			});
			
			// set popup
			if (this.homeEventHandler.getPopup() == null) {
				this.homeEventHandler.setPopup(new PopupList("", null, null));
			}
			// set searchList
			if (this.homeEventHandler.getSearchList() == null) {
				this.homeEventHandler.setSearchList(new SearchList("Search", null));
			}
			// set toast
			if (this.homeEventHandler.getToast() == null) {
				this.homeEventHandler.setToast(new Toast(""));
			}
		}
	},
	
	initEditTopArea : function() {
		var homeNameInput = ".edit_top .ui-search",
			backgroundArea = ".edit_top .pop-bg",
			addSegmentButton = ".edit_top .ui-has-button a:eq(0)";
		
		jQuery(homeNameInput + " input[type=text]").focus(function(event) {
			var position = jQuery(homeNameInput).outerHeight(true);
			jQuery(backgroundArea).css({ height : window.innerHeight - position, top : position });
		}).blur(function(event) {
			jQuery(backgroundArea).css("height", 0);
		});
		
		jQuery(backgroundArea).unbind("click").bind("click", function(event) {
			jQuery(this).css("height", 0);
		}).unbind("mousewheel").bind("mousewheel", function(event) {
			event.preventDefault();
		});
		jQuery("#wrap").unbind("touchstart mousedown").bind("touchstart mousedown", function(event) {
			if ((event.target !== jQuery(homeNameInput + " input[type=text]").get(0)) && jQuery(homeNameInput + " input[type=text]").is(":focus")) {
				jQuery(homeNameInput + " input[type=text]").blur();
			}
		});
		
		jQuery(addSegmentButton).attr("href", "javascript:chs.setHash('addSegment');");		// set add segment div
	},
	
	/* hash change related function */
	/**
	 * 
	 */
	configHashChangeEvent : function() {
		var priority = {
			"home" : 0,				"editHome" : 1,			"webclip" : 1,
			"addSegment" : 2,		"editDetail" : 2,		"settings" : 2,			"multipleHome" : 2,
			"addWebclipToHome" : 2, "editWebclip" : 2,
			"optionSearch" : 2,		"getMoreHome" : 3
		},
			actionTable = [{ 'from' : 'home',			'to' : 'editHome',		'action' : this.startSegmentEditMode },
		                   { 'from' : 'editHome',		'to' : 'home',			'action' : this.finishSegmentEditMode },
		                   { 'from' : 'editHome',		'to' : 'optionSearch',	'action' : this.startOptionSearchMode },
		                   { 'from' : 'optionSearch',	'to' : 'editHome',		'action' : this.finishOptionSearchMode },
		                   { 'from' : 'editHome',		'to' : 'addSegment',	'action' : this.startAddSegmentMode },
		                   { 'from' : 'addSegment',		'to' : 'editHome',		'action' : this.finishAddSegmentMode },
		                   { 'from' : 'addSegment',		'to' : 'optionSearch',	'action' : this.startOptionSearchMode },
		                   { 'from' : 'editHome',		'to' : 'editDetail',	'action' : this.startSegmentEditDetail },
		                   { 'from' : 'editDetail',		'to' : 'editHome',		'action' : this.finishSegmentEditDetail },
		                   { 'from' : 'addSegment',		'to' : 'editDetail',	'action' : this.startSegmentEditDetail },
		                   { 'from' : 'editDetail',		'to' : 'optionSearch',	'action' : this.startOptionSearchMode },
		                   { 'from' : 'optionSearch',	'to' : 'editDetail',	'action' : function(popupInfo) {
		                	   this.finishOptionSearchMode();
		                	   this.startSegmentEditDetail(popupInfo);
		                   } },
		                   { 'from' : 'editHome',		'to' : 'multipleHome',	'action' : this.startMultipleHomeScreen },
		                   { 'from' : 'multipleHome',	'to' : 'editHome',		'action' : this.finishMultipleHomeScreen },
		                   { 'from' : 'home',			'to' : 'webclip',		'action' : this.startWebclipMode },
		                   { 'from' : 'webclip',		'to' : 'home',			'action' : this.startHomeScreenMode },
		                   { 'from' : 'webclip',		'to' : 'editWebclip',	'action' : this.startWebclipEditMode },
		                   { 'from' : 'editWebclip',	'to' : 'webclip',		'action' : this.finishWebclipEditMode }];
		this.hashChange = new HashChange(this, location.pathname, priority, actionTable);
		
		jQuery(window).bind("hashchange", { hashChange : this.hashChange }, this.hashChange.onHashChange);
	},
	
	/**
	 * @function
	 * @param hash
	 * @param actionParams
	 */
	setHash : function(hash, actionParams) {
		jQuery("#log").append("in setHash(), hash : " + hash);
		this.hashChange.setHash(hash, actionParams);
	},
	/* hash change related function end */
	
	/**
	 * 
	 */
	refreshHome : function() {
		// Hide currently unused elements
		jQuery(".edit_top").hide();		// hide edit top
		jQuery("#homeContainer > .arrow_container").hide();		// hide home arrow container
		jQuery("#chsPopup, #searchContainer, #toast").hide();
		
		// remove current chs
		jQuery(".home_container").removeClass("change");
		jQuery(".home_container > .moving_area").html("").removeAttr("style");
		jQuery("#webclip > .screen > ul").html("");
	
		this.startHomeScreenMode(this);
		
		this.initEvent(true);
		this.homeManager.loadHome();
	},

	/**
	 * set Footer values and event handlers
	 * @function
	 * @param String mode
	 * @return none
	 */
	setFooter : function(mode) {
		var cloudHomeScreen = this;
		
		// change current mode
		cloudHomeScreen.homeEventHandler.setCurrentMode(mode);
	
//		if (isMobile("iPad") || isMobile("iPhone")) {
			/* for iPad... footer button values are not changed in iPad */
			setTimeout(function() {
				cloudHomeScreen.changeFooterStatus(mode);
			}, 1);
//		} else {
//			cloudHomeScreen.changeFooterStatus(mode);
//		}
	},
	
	changeFooterStatus : function(mode) {
		if (mode == "home") {
			jQuery("#footer button:first").html("Web clips");
			jQuery("#footer a:first").attr("href", "javascript:chs.setHash('webclip');");
			jQuery("#footer button:last").html("Edit home");
			jQuery("#footer a:last").attr("href", "javascript:chs.homeEventHandler.checkEditHomeCondition();");
		} else if (mode == "home edit") {
			jQuery("#footer button:first").html("Done");
			jQuery("#footer a:first").attr("href", "javascript:chs.setHash('home');");
			jQuery("#footer button:last").html("Change");
			jQuery("#footer a:last").attr("href", "javascript:chs.setHash('multipleHome');");
		} else if (mode == "webclip") {
			jQuery(".footer footer li:first").html("Add to home");
			jQuery(".footer footer a:first").attr("href", "javascript:chs.addWebclipsToCurrentHome(true);");
			jQuery(".footer footer li:last").html("Edit");
			jQuery(".footer footer a:last").attr("href", "javascript:chs.setHash('editWebclip');");
		} else if (mode == "webclip edit") {
			jQuery(".footer footer li:first").html("Done");
			jQuery(".footer footer a:first").attr("href", "javascript:chs.setHash('webclip');");
			jQuery(".footer footer li:last").html("");
			jQuery(".footer footer a:last").removeAttr("href");
		} else if (mode == "multiple home") {
			jQuery("#footer button:first").html("Create");
			jQuery("#footer a:first").attr("href", "javascript:chs.addNewHome();");
			jQuery("#footer button:last").html("Get more");
			jQuery("#footer a:last").removeAttr("href");
		} else {

		}
	},

	/**
	 * start Home Edit Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	startSegmentEditMode : function() {
		this.setFooter("home edit");
		this.initAccountManager();
		this.homeManager.startSegmentEditMode();
	},

	/**
	 * finish Home Edit Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	finishSegmentEditMode : function() {
		var homeEventHandler = this.getEventHandler();
		
		this.setFooter("home");
		this.homeManager.finishSegmentEditMode();

		// DB update
		if (chsConstants.isCloudPhone && homeEventHandler.checkOnLine()) {
			homeEventHandler.showStatusBar("Start Server sync...");
			this.syncManager.server_sync(function() {
				homeEventHandler.hideStatusBar();
			}, function(message) {
				homeEventHandler.showErrorMessage("Server Sync Error : " + message);
				homeEventHandler.hideStatusBar();
			});
		}
	},

	/**
	 * start Segment Edit Detail
	 * @function
	 * @param Event event
	 * @return none
	 */
	startSegmentEditDetail : function(popupInfo) {
		this.setFooter("edit detail");
		
		this.getEventHandler().changeHomeWrapperStatus();
		
		this.showPopup(popupInfo);
	},

	/**
	 * finish Segment Edit Detail
	 * @function
	 * @param Event event
	 * @return none
	 */
	finishSegmentEditDetail : function() {
		this.setFooter("home edit");
		
		this.homeEventHandler.changeHomeWrapperStatus();
		
		this.homeEventHandler.getPopup().hide();
	},

	/**
	 * start Segment Addition Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	startAddSegmentMode : function() {
		this.homeEventHandler.changeHomeWrapperStatus();
		
		this.showPopup(this.segmentManager.getPopupInfo("add segment"));
	},
	
	/**
	 * show PopupList
	 * @function
	 * @param Object info
	 * @return none
	 */
	showPopup : function(info) {
		var cloudHomeScreen = chs;
		
		var popup = cloudHomeScreen.homeEventHandler.getPopup();
		if (popup) {
			popup.init(info.title, info.list, info.buttons);
			popup.show();
			
			jQuery(".ui-pop").unbind("mousewheel touchmove").bind("mousewheel touchmove", function(event) {
				event.preventDefault();		// prevent browser scroll
			});
			
			if (info.onBackgroundClick) {
				popup.setOnBackgroundClick(info.onBackgroundClick);
			}
			
			// refresh popuplist iscroll
			cloudHomeScreen.homeEventHandler.setVerticalIScroll("popupList_iscroll", false);
			
			cloudHomeScreen.homeEventHandler.setPopup(popup);
		}
	},
	
	/**
	 * show SearchList
	 * @function
	 * @param info
	 * @return none
	 */
	showSearchList : function(info) {
		var searchList = this.homeEventHandler.getSearchList();
		if (searchList) {
			searchList.init(info.placeholder, info.list, info.buttons, info.caller);
			
			// hide home container
			searchList.show();
			
			jQuery(".search_container").unbind("mousewheel touchmove").bind("mousewheel touchmove", function(event) {
				event.preventDefault();		// prevent browser scroll
			});
			
			// fadeIn �띾룄����쓳�섍린 �꾪븳 setTimeout...
			var cloudHomeScreen = this;
			setTimeout(function() {
				// refresh searchlist iscroll
				cloudHomeScreen.homeEventHandler.setVerticalIScroll("searchList_iscroll", false);
				
				cloudHomeScreen.homeEventHandler.setSearchList(searchList);
			}, 500);
		}
	},
	
	/**
	 * show Toast
	 * @function
	 * @param String message
	 * @return none
	 */
	showToast : function(message) {
		var toast = this.homeEventHandler.getToast();
		if (toast) {
			toast.init(message);
		}
		
//		toast.show();
		this.homeEventHandler.setToast(toast);
	},

	/**
	 * add new segment into current home
	 * @function
	 * @param Event event
	 * @return none
	 */
	addSegment : function(event) {
		var cloudHomeScreen = event.data.cloudHomeScreen,
			sgmtId = event.data.sgmtId;

		if (event.type == "tap") {
			var type = cloudHomeScreen.segmentManager.getSegmentType(sgmtId);
			if (type == "news") {
				// if segment is news, execute category selection logic
				cloudHomeScreen.showPopup(cloudHomeScreen.segmentManager.getPopupInfo("news"));
			} else if (type == "gallery") {
				var hash = "editDetail",
					actionParams = cloudHomeScreen.getSegmentManager().getPopupInfo("gallery add photos from", { sgmtId : sgmtId });
				cloudHomeScreen.setHash(hash, actionParams);
			} else if (type == "snsfeeds") {
				var hash = "editDetail",
					actionParams = cloudHomeScreen.getSegmentManager().getPopupInfo("snsfeeds", { sgmtId : sgmtId });
				cloudHomeScreen.setHash(hash, actionParams);
			} else if ((type == "contacts") || (type == "shortcuts") || (type == "weather") || (type == "stock")) {
				// hide add segment popup
				cloudHomeScreen.homeEventHandler.getPopup().hide();
				
				// show search list
				var segmentObj = cloudHomeScreen.segmentManager.getNewSegmentObject(sgmtId);
				segmentObj.setHomeId(cloudHomeScreen.homeManager.getCurrentHomeId());
				segmentObj.setSegmentId(sgmtId);
				
				var hash = "optionSearch",
					actionParams = segmentObj;
				cloudHomeScreen.setHash(hash, actionParams);
			} else {
				cloudHomeScreen.segmentManager.addSegment(sgmtId);
				cloudHomeScreen.setHash("editHome");
			}
		}
	},

	/**
	 * finish Segment Addition Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	finishAddSegmentMode : function() {
		this.homeEventHandler.changeHomeWrapperStatus();
		
		this.homeEventHandler.getPopup().hide();
		// change the width of screen class
		jQuery("section .screen").css("width", window.innerWidth-40 + "px");
	},

	/**
	 * start Cloud Home Screen Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	startHomeScreenMode : function() {
		var homeEventHandler = this.getEventHandler();
		
		this.setFooter("home");
		// show home container, hide webclip list
		jQuery("#homeWrapper").show();
		jQuery("#webclipWrapper").hide();
		
		if (chsConstants.isCloudPhone && homeEventHandler.checkOnLine()) {
			homeEventHandler.showStatusBar("Start Server sync...");
			this.syncManager.server_sync(function() {
				homeEventHandler.hideStatusBar();
			}, function(message) {
				homeEventHandler.showErrorMessage("Server Sync Error : " + message);
				homeEventHandler.hideStatusBar();
			});
		}
	},

	/**
	 * start Webclip Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	startWebclipMode : function() {
		var webclipManager = this.getWebclipManager();
		
		this.setFooter("webclip");
		// load webclip list
		if (webclipManager.getWebclipLoaded() == false) {
			webclipManager.setWebclipLoaded(true);
			this.loadWebclips();
		}
		
		// set checkbox
		webclipManager.setWebclipCheckbox();
		// show webclip list, hide home container
		jQuery("#homeWrapper").hide();
		jQuery("#webclipWrapper").show();
	},

	/**
	 * load Webclips
	 * @function
	 * @param none
	 * @return none
	 */
	loadWebclips : function() {
		this.webclipManager.loadWebclips();
		this.homeEventHandler.refreshScreenWidth();
		
		jQuery("iframe").blur();
	},

	/**
	 * start Webclip Edit Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	startWebclipEditMode : function() {
		this.setFooter("webclip edit");
		this.webclipManager.startWebclipEditMode();
	},

	/**
	 * finish Webclip Edit Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	finishWebclipEditMode : function() {
		var homeEventHandler = this.getEventHandler();
		
		this.setFooter("webclip");
		this.webclipManager.finishWebclipEditMode();

		// DB update
		if (chsConstants.isCloudPhone && homeEventHandler.checkOnLine()) {
			homeEventHandler.showStatusBar("Start Server sync...");
			this.syncManager.server_sync(function() {
				homeEventHandler.hideStatusBar();
			}, function(message) {
				homeEventHandler.showErrorMessage("Server Sync Error : " + message);
				homeEventHandler.hideStatusBar();
			});
		}
	},
	
	/**
	 * add selected Webclips to current Cloud Home Screen
	 * @param Event event
	 * @return none
	 */
	addWebclipsToCurrentHome : function(flag) {
		var hash = "home",
			actionParams = this;
		
		this.webclipManager.addWebclipsToCurrentHome(flag);
		this.setHash(hash, actionParams);
	},

	/**
	 * start Multiple Home Screen Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	startMultipleHomeScreen : function() {
		this.setFooter("multiple home");
		this.homeManager.startMultipleHomeScreen();
	},

	/**
	 * finish Multiple Home Screen Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	finishMultipleHomeScreen : function(homeId) {
		var homeManager = this.getHomeManager();
		
		if (homeId == null) {
			homeId = homeManager.getCurrentHomeId();
		}
		this.setFooter("home edit");
		homeManager.finishMultipleHomeScreen(homeId);

		// update layouts
		this.updateLayout();
	},

	/**
	 * add new Home
	 * @function
	 * @param Event event
	 * @return none
	 */
	addNewHome : function() {
		this.setFooter("home edit");
		this.homeManager.addNewHome();
	},

	/**
	 * update chs_layout information
	 * @function
	 * @param none
	 * @return none
	 */
	updateLayout : function(pushFlag) {
		var cloudHomeScreen = this,
			homeEventHandler = cloudHomeScreen.getEventHandler();
		
		console.log("layout update, push : " + pushFlag);
		if (homeEventHandler.checkOnLine()) {
			var layouts = this.layoutStringify();
			console.log("[updateLayout] layouts : " + layouts);
			homeEventHandler.showStatusBar("Update CHS layout...");
			if (chsConstants.isCloudPhone) {
				var valueobject = new SyncManager.CHSLayout();
				valueobject._layouts = layouts;
				this.syncManager.update(valueobject, function() {
					homeEventHandler.hideStatusBar();
				}, function(message) {
					homeEventHandler.showErrorMessage(message);
					homeEventHandler.hideStatusBar();
				}, false); 
			} else {
				var url = "/aphone/chs/layout/update",
					type = "POST",
					params = "layouts=" + encodeURIComponent(layouts);
				
				if (pushFlag) {
					params += "&push=true";
				}
				
				if (chsConstants.workerExist) {
					var data = { url : url, type : type, data : params };
					homeEventHandler.executeWorker("updateLayout", data, function(xhr) {
						cloudHomeScreen.updateLayoutCallback(xhr);
					});
				} else {
					jQuery.ajax({
						url : url,
						type : type,
						data : params,
						complete : function(xhr) {
							if (xhr.readyState == 4) {
								cloudHomeScreen.updateLayoutCallback(xhr);
							}
						}
					});
				}
			}
			
			// set local storage
			homeEventHandler.setLocalStorage("homeManagerInfo", cloudHomeScreen.layoutStringify());
			
			var segmentManagerInfo = cloudHomeScreen.segmentManager.getSegmentManagerInfo();
			homeEventHandler.setLocalStorage("segmentManagerInfo", JSON.stringify(segmentManagerInfo));
		} else {
			homeEventHandler.showErrorMessage("Can't update chs_layout. (offline)");
		}
	},
	
	updateLayoutCallback : function(xhr) {
		var homeEventHandler = this.getEventHandler();
		
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
					// success message
					console.log("CHS_LAYOUT UPDATE SUCCESS");
					homeEventHandler.hideStatusBar();
				} else {
					// error message
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
		}
	},
	
	deleteHomeInfo : function(homeId) {
		var cloudHomeScreen = this,
			homeEventHandler = this.getEventHandler();
		
		if (homeEventHandler.checkOnLine()) {
			homeEventHandler.showStatusBar("Delete Home Information...");
			if (chsConstants.isCloudPhone) {
				var valueObject = new SyncManager.CHSSegmentOption();
				valueObject._home_id = homeId;
				cloudHomeScreen.getSyncManager().remove(valueObject, function() {
					homeEventHandler.hideStatusBar();
				}, function(message) {
					homeEventHandler.showErrorMessage(message);
					homeEventHandler.hideStatusBar();
				}, false);
				
				cloudHomeScreen.updateLayout();
			} else {
				var url = "/aphone/chs/home/delete",
					type = "POST",
					params = "homeId=" + encodeURIComponent(homeId) + "&layouts=" + encodeURIComponent(this.layoutStringify());
				
				if (chsConstants.workerExist) {
					var data = { url : url, type : type, data : params };
					homeEventHandler.executeWorker("deleteHomeSegments", data, function(xhr) {
						cloudHomeScreen.deleteHomeSegmentCallback(xhr, homeId);
					});
				} else {
					jQuery.ajax({
						url : url,
						type : type,
						data : params,
						complete : function(xhr) {
							if (xhr.readyState == 4) {
								cloudHomeScreen.deleteHomeSegmentCallback(xhr, homeId);
							}
						}
					});
				}
			}
		}
	},
	
	deleteHomeSegmentCallback : function(xhr, homeId) {
		var homeEventHandler = this.getEventHandler();
		
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
					// success message
					console.log("CHS_SEGMENT_OPTION home_id " + homeId + " DELETE SUCCESS");
					homeEventHandler.hideStatusBar();
				} else {
					// error message
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
		}
	},
	
	/**
	 * start Segment Edit Detail Option Search Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	startOptionSearchMode : function(segmentObj) {
		this.getEventHandler().changeHomeWrapperStatus();
		
		this.showSearchList(this.segmentManager.getSearchListInfo(segmentObj));
	},
	
	/**
	 * finish Segment Edit Detail Option Search Mode
	 * @function
	 * @param Event event
	 * @return none
	 */
	finishOptionSearchMode : function() {
		var homeEventHandler = this.getEventHandler();
		
		homeEventHandler.changeHomeWrapperStatus();
		
		homeEventHandler.getSearchList().hide();
		/** exception handling */
		homeEventHandler.getPopup().hide();
	}
};

/**
 * @class HomeManager
 * @constructor
 * @memberOf CloudHomeScreen
 * @param CloudHomeScreen cloudHomeScreen
 */
var HomeManager = function(cloudHomeScreen) {
	this.cloudHomeScreen = cloudHomeScreen;
	this.homeList = [];
	this.currentHomeId = null;
};

/**
 * @lends HomeManager.prototype
 */
HomeManager.prototype = {
	/**
	 * set 'homeList' instance
	 * @function
	 * @param {Array} homeList
	 */
	setHomeList : function(homeList) {
		this.homeList = homeList;
	},

	/**
	 * set 'currentHomeId' instance
	 * @function
	 * @param {String} homeId
	 */
	setCurrentHomeId : function(homeId) {
		this.currentHomeId = homeId;
	},

	/**
	 * get 'HomeList' instance
	 * @function
	 * @returns {Array} this.homeList
	 */
	getHomeList : function() {
		return this.homeList;
	},
	
	getHomeListExceptCurrentHomeId : function() {
		var list = [];
		
		for (var i=0, count=this.homeList.length ; i<count ; ++i) {
			var homeId = this.homeList[i].id;
			
			if (homeId != this.currentHomeId) {
				list.push(homeId);
			}
		}
		
		return list;
	},

	/**
	 * get 'currentHomeId' instance
	 * @function
	 * @returns {String} this.currentHomeId
	 */
	getCurrentHomeId : function() {
		return this.currentHomeId;
	},

	/**
	 * get the index of current home
	 * @function
	 * @returns {Number} index
	 */
	getCurrentHomeIndex : function() {
		for (var i=0, homeCount=this.homeList.length ; i<homeCount ; ++i) {
			if (this.homeList[i].id == this.currentHomeId) {
				return i;
			}
		}

		return -1;
	},
	
	/**
	 * get the home name of parameter 'homeId'
	 * @function
	 * @param {String} homeId
	 * @returns {String} home_name
	 */
	getHomeName : function(homeId) {
		for (var i=0, homeCount=this.homeList.length ; i<homeCount ; ++i) {
			if (this.homeList[i].id == homeId) {
				return this.homeList[i].name;
			}
		}
		
		return "";
	},
	
	/**
	 * get the home name of current home
	 * @function
	 * @returns {String} current_home_name
	 */
	getCurrentHomeName : function() {
		return this.getHomeName(this.currentHomeId);
	},

	/**
	 * initialize HomeManager
	 * @function
	 * @param {Array} homeList
	 * @param {String} currentHomeId
	 */
	initialize : function(homeList, homeId) {
		this.setHomeList(homeList);
		this.setCurrentHomeId(homeId);
	},

	/**
	 * load home
	 * <li>caller : CloudHomeScreen.loadHome()</li>
	 * @function
	 */
	loadHome : function() {
		// create all segment containers
		for (var i=0, homeCount=this.homeList.length ; i<homeCount ; ++i) {
			this.createSegmentContainer(this.homeList[i].id);
		}
		// fill segment contents into current home's segment container
		this.configSegmentContainer(this.getCurrentHomeId());

		jQuery(".icon-delete").hide();
		jQuery(".home_cover").hide();
	},

	/**
	 * load all homes except current home (current home was already loaded.)
	 * @function
	 */
	loadOtherHome : function() {
		for (var i=0, homeCount=this.homeList.length ; i<homeCount ; ++i) {
			if (this.homeList[i].id == this.currentHomeId) {
				continue;
			}

			// set options of other home if options do not exist
			var layout = this.cloudHomeScreen.getSegmentManager().getLayout(this.homeList[i].id);
			if (layout.length != 0) {
				var firstOption = this.cloudHomeScreen.getSegmentManager().getSegmentOption(this.homeList[i].id, layout[0]);
				if ((firstOption == null) || (firstOption == undefined)) {
					this.cloudHomeScreen.getSegmentManager().initSegmentOptions(this.homeList[i].id);
				}
			}

			// fill all segment contents
			this.configSegmentContainer(this.homeList[i].id);

			// load segments
			this.cloudHomeScreen.getSegmentManager().loadSegments(this.homeList[i].id);
			
			// hide delete buttons
			jQuery(".icon-delete").hide();
		}

		this.cloudHomeScreen.getEventHandler().setOtherHomeLoaded(true);
	},

	/**
	 * create one segment_container
	 * @function
	 * @param {String} homeId
	 */
	createSegmentContainer : function(homeId) {
		if (jQuery("#" + homeId + ".segment_container").size() == 0) {
			// Append new segment container to home container
			var homeStr = 	"<ol id=\"" + homeId + "\" class=\"segment_container\">" +
								"<div class=\"icon-delete\"></div>" +
								"<div class=\"home_cover\"></div>" +
								"<h2></h2>" +
								"<ul></ul>" +
							"</ol>";
			jQuery(".home_container > .moving_area").append(homeStr);

			// bind event into home delete button
			this.setHomeDelBtn(homeId);

			// change the width of home moving area
			var areaWidth = this.getHomeAreaWidth();
			var homeWidth = this.getHomeWidth();
			this.changeHomeAreaWidth(areaWidth + homeWidth);
		}
	},

	/**
	 * set home_delete_button
	 * @function
	 * @param {String} homeId
	 */
	setHomeDelBtn : function(homeId) {
		var eventType = chsConstants.tapReplaceEvent;
		jQuery("#" + homeId + " .icon-delete").css("cursor", "pointer").unbind("click").bind("click", { homeManager : this, homeId : homeId }, function(event) {
			if (event.currentTarget === event.originalEvent.currentTarget) {
				if (chsConstants.isMobile || (event.button === 0)) {
					var homeManager = event.data.homeManager,
						homeId = event.data.homeId,
						homeEventHandler = homeManager.cloudHomeScreen.getEventHandler();
					if (homeEventHandler.segmentScroll["homeContainer"] && !homeEventHandler.segmentScroll["homeContainer"].isMove) {
						homeManager.deleteHome(homeId);
					}
				}
			}
		});
	},

	/**
	 * delete home
	 * <li>call time : when user click home_delete_button</li>
	 * @function
	 * @param Event event
	 */
	deleteHome : function(homeId) {
		var cloudHomeScreen = this.cloudHomeScreen,
			homeManager = this,
			homeEventHandler = cloudHomeScreen.getEventHandler();
		
		this.deleteHomeInfo(homeId);		// update instance value
		// delete segment container
		jQuery("#" + homeId).fadeOut("fast", function() {
			jQuery(this).remove();
			
			/* �덉쇅泥섎━ : 紐⑤뱺 home����젣�섎㈃ ��home �섎굹瑜�異붽��쒕떎. */
			if (homeManager.homeList.length > 0) {
				homeManager.changeHomeAreaWidth();
				
				var id = "homeContainer";
				homeEventHandler.refreshIScroll(id);
				homeEventHandler.scrollToPage(id, homeManager.getCurrentHomeIndex(), 0, 0);
				homeEventHandler.setIScrollHorizontalButtons(id, { prev : id + "_slidePrev", next : id + "_slideNext" });
				
				// update db
//				cloudHomeScreen.updateLayout();
				cloudHomeScreen.deleteHomeInfo(homeId);
			} else {
				homeManager.addNewHome();
			}
		});
	},

	/**
	 * delete home information from HomeManager and SegmentManager
	 * @function
	 * @param homeId
	 */
	deleteHomeInfo : function(homeId) {
		// delete homeInfo from segment manager
		this.cloudHomeScreen.getSegmentManager().deleteHomeInfo(homeId);

		// delete homeId from home manager
		for (var i=0, homeCount=this.homeList.length ; i<homeCount ; ++i) {
			if (this.homeList[i].id == homeId) {
				// change current home id if current home is deleted
				if (this.currentHomeId == homeId) {
					if (i == homeCount - 1) {
						this.setCurrentHomeId((i != 0) ? this.homeList[i-1].id : null);
					} else {
						this.setCurrentHomeId(this.homeList[i+1].id);
					}
				}

				this.homeList.splice(i, 1);
				break;
			}
		}
	},

	/**
	 * set homeList and currentHomeId
	 * @function
	 * @param {Array} homeList
	 * @param {String} homeId
	 */
	updateHomeInfo : function(homeList, homeId) {
		this.initialize(homeList, homeId);
	},

	/**
	 * change home_container's moving_area width
	 * @function
	 * @param {Number} width
	 */
	changeHomeAreaWidth : function() {
		var width = 0;
		var segmentContainers = jQuery("#homeContainer ol");
		for (var i=0 ; i<segmentContainers.size() ; ++i) {
			width += jQuery("#homeContainer ol:eq(" + i + ")").outerWidth(true);
		}
		jQuery(".home_container > .moving_area").css("width", width);
	},

	/**
	 * get home_container's moving_area width
	 * @function
	 * @returns {Number} width
	 */
	getHomeAreaWidth : function() {
		return jQuery(".home_container > .moving_area").outerWidth(true);
	},

	/**
	 * get the width of segment_container
	 * @function
	 * @returns {Number} width
	 */
	getHomeWidth : function() {
		return jQuery(".segment_container").outerWidth(true);
	},

	/**
	 * configure segment_container (set events and create segments)
	 * @function
	 * @param {String} homeId
	 */
	configSegmentContainer : function(homeId) {
		var cloudHomeScreen = this.cloudHomeScreen;
		var sortableSelector = "#" + homeId + " > ul";
		jQuery(sortableSelector).sortable();
		jQuery(sortableSelector).sortable("option", {
			"grid" : [10000, 1],
			"cursor" : "crosshair",
			"opacity" : 0.6,
			"scroll" : true,
			"z-index" : 12,
//			"revert" : true,
			"tolerance" : "pointer",
			"axis" : "y"
		});
		/*if (chsConstants.isCloudPhone) {
			jQuery(sortableSelector).sortable("option", "delay", 2000);
		}*/
		jQuery(sortableSelector).sortable({
			// stop sorting and DOM position is changed
			update : function(event, ui) {
				cloudHomeScreen.getEventHandler().onSegmentOrderChanged(homeId);
			}
		});
		
		jQuery("#" + homeId + " > h2").html(this.getHomeName(homeId));
		
		var layout = this.cloudHomeScreen.getSegmentManager().getLayout(homeId);
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			var sgmtId = layout[i];
			if (sgmtId && (sgmtId != "") && (sgmtId.indexOf("NEWS_000") == -1)) {
				this.cloudHomeScreen.getSegmentManager().createSegment(homeId, sgmtId);
			}
		}

		jQuery(sortableSelector).sortable("option", "disabled", true);
	},

	/**
	 * start Home Edit Mode
	 * <li>caller : CloudHomeScreen.startSegmentEditMode()</li>
	 * @function
	 */
	startSegmentEditMode : function() {
		// enable home container sortable
		jQuery("#" + this.currentHomeId + " > ul").sortable("option", "disabled", false);
		
		// add edit class into elements that have segment class
		jQuery("#" + this.currentHomeId + " .segment").addClass("edit");
		// show delete buttons
		jQuery("#" + this.currentHomeId + " .segment .icon-delete").show();
		// show add buttons
		jQuery("#" + this.currentHomeId + " .add").show();
		// change the width of screen class
		var pageWidth = window.innerWidth;
		jQuery("section .screen").css("width", pageWidth-40 + "px");
		
		// show edit top
		jQuery(".edit_top").show();
		// display the name of current home
		jQuery(".edit_top input").attr("value", this.getCurrentHomeName());
		
		// execute additional action repectively
		var layout = this.cloudHomeScreen.getSegmentManager().getLayout(this.currentHomeId);
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			var segmentObj = this.cloudHomeScreen.getSegmentManager().getSegmentObject(this.currentHomeId, layout[i]);
			if (segmentObj && segmentObj.startEditMode) {
				segmentObj.startEditMode();
			}
		}
	},

	/**
	 * finish Home Edit Mode
	 * @function
	 */
	finishSegmentEditMode : function() {
		// disable home container sortable
		jQuery("#" + this.currentHomeId + " > ul").sortable("option", "disabled", true);

		// remove edit class from elements that have segment class
		jQuery("#" + this.currentHomeId + " .segment").removeClass("edit");
		// hide delete buttons
		jQuery("#" + this.currentHomeId + " .segment .icon-delete").hide();
		// hide add buttons
		jQuery("#" + this.currentHomeId + " .add").hide();
		// change the width of screen class
		var pageWidth = window.innerWidth;
		jQuery("section .screen").css("width", pageWidth + "px");
		
		// hide edit top
		jQuery(".edit_top").hide();
		// save the name of current home
		var homeName = jQuery(".edit_top input").attr("value");
		this.homeList[this.getCurrentHomeIndex()].name = ((homeName == "") ? "Unnamed Home" : homeName);
		jQuery("#" + this.currentHomeId + " > h2").html(this.getCurrentHomeName());
		
		this.cloudHomeScreen.updateLayout(true);
		
		// execute additional action repectively
		var layout = this.cloudHomeScreen.getSegmentManager().getLayout(this.currentHomeId);
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			var segmentObj = this.cloudHomeScreen.getSegmentManager().getSegmentObject(this.currentHomeId, layout[i]);
			if (segmentObj && segmentObj.finishEditMode) {
				segmentObj.finishEditMode();
			}
		}
	},

	/**
	 * start Multiple Home Screen Mode
	 * @function
	 */
	startMultipleHomeScreen : function() {
		var homeManager = this,
			cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = this.cloudHomeScreen.getEventHandler();
		
		// set home_container and segment_containers
		this.finishSegmentEditMode();		// finish current edit mode
		if (homeEventHandler.getOtherHomeLoaded() == false) {
			this.loadOtherHome();		// load other homes
		}
		jQuery(".segment_container .arrow_container").hide();		// hide arrow_containers of segment_container
		jQuery(".segment_container").show();
		jQuery(".segment_container > .icon-delete").show();
		
		jQuery(".home_container").addClass("change");		// minimize home (add class)
//		jQuery(".home_container.change > .moving_area").css("height", jQuery(".segment_container").outerHeight(true));
		jQuery(".home_container > .arrow_container").show();
		
		// bind event into home cover
		jQuery(".home_cover").each(function(i) {
			var homeId = jQuery(this).parent().attr("id"),
				hash = "editHome",
				actionParams = homeId,
				eventType = chsConstants.tapReplaceEvent;
			
//			jQuery(this).attr("href", "javascript:chs.setHash('" + hash + "', '" + actionParams + "');");
			jQuery(this).unbind(eventType).bind(eventType, function(event) {
				if (isMyEvent(event) && isLeftButtonClick(event)) {
					var segmentScrollInfo = homeEventHandler.segmentScroll["homeContainer"];
					
					if (segmentScrollInfo && !segmentScrollInfo.isMove) {
						cloudHomeScreen.setHash(hash, actionParams);
					}
				}
			});
		}).show();
		
		// downsize segment_container
		var pageWidth = window.innerWidth;
		jQuery(".segment_container > ul").each(function() {
			var containerHeight = jQuery(this).outerHeight(true);
			var style = "-webkit-transform:scale(0.7,0.7) translate(" + -(pageWidth*0.15) + "px, " + -(containerHeight*0.15/0.7) + "px);" +
						"-moz-transform:scale(0.7,0.7) translate(" + -(pageWidth*0.15) + "px, " + -(containerHeight*0.15/0.7) + "px);" +
						"-o-transform:scale(0.7,0.7) translate(" + -(pageWidth*0.15) + "px, " + -(containerHeight*0.15/0.7) + "px);" +
						"-ms-transform:scale(0.7,0.7) translate(" + -(pageWidth*0.15) + "px, " + -(containerHeight*0.15/0.7) + "px);";
			jQuery(this).attr("style", style);
		});
		
		// change moving_area width
		homeEventHandler.refreshScreenWidth();
		this.changeHomeAreaWidth();
		
		// set iscroll
		if (homeEventHandler.hasIScroll(id)) {
			homeEventHandler.refreshIScroll(id);
			homeEventHandler.enableIScroll(id);
		} else {
			var id = "homeContainer";
			var options = { hScroll : true, vScroll : false, hScrollbar : false, vScrollbar : false, hideScrollbar : false, fadeScrollbar : false, desktopCompatibility : true, snap : "ol", momentum : false, hidden : false };
			var buttons = {
					prev : "#homeContainer_slidePrev",
					next : "#homeContainer_slideNext"
			};
			
			homeEventHandler.createIScroll(id, options, buttons);
		}
		homeEventHandler.scrollToPage(id, this.getCurrentHomeIndex(), 0, 0);
	},

	/**
	 * finish Multiple Home Screen Mode
	 * @function
	 * @param Event event
	 * @param {String} homeId
	 */
	finishMultipleHomeScreen : function(homeId) {
		var homeManager = this;
		this.setCurrentHomeId(homeId);

		var id = "homeContainer";
		var homeEventHandler = this.cloudHomeScreen.getEventHandler();
		homeEventHandler.disableIScroll(id);
		homeEventHandler.scrollTo(id, 0, 0, 0);

		jQuery("#homeContainer > .arrow_container").hide();
		jQuery(".home_cover").hide();
		jQuery(".home_container").removeClass("change");
//		jQuery(".home_container > .moving_area").css("height", 0);
		jQuery(".segment_container").each(function() {
			var id = jQuery(this).attr("id");
			if (id != homeId) {
				jQuery(this).hide();
			}
		});
		jQuery(".segment_container > ul").removeAttr("style");
		jQuery(".segment_container > .icon-delete").hide();
		jQuery(".segment_container .arrow_container").show();
		
		homeEventHandler.refreshScreenWidth();
		
		// restart edit mode about current home
		this.startSegmentEditMode();
	},

	/**
	 * create new segment_container
	 * @function
	 */
	addNewHome : function() {
		var today = new Date();
		var defaultHomeInfo = {
			homeId : "home" + today.getTime(),
			homeName : "Home_" + today.getTime(),
			layout : [ "SGMT_0000000000001" ]
		};

		// update homeList
		this.homeList.push({ id : defaultHomeInfo.homeId, name : defaultHomeInfo.homeName });

		// update currentHomeId
		this.currentHomeId = defaultHomeInfo.homeId;

		// update homeInfo
		this.cloudHomeScreen.getSegmentManager().addHomeInfo(defaultHomeInfo);
		this.cloudHomeScreen.getSegmentManager().initSegmentOptions(this.currentHomeId);

		// create segment container
		this.createSegmentContainer(this.currentHomeId);
		this.configSegmentContainer(this.currentHomeId);

		// load segments
		this.cloudHomeScreen.getSegmentManager().loadSegments(this.currentHomeId);

		// finish multiple home screen
		var hash = "editHome", actionParams = this.currentHomeId;
		this.cloudHomeScreen.setHash(hash, actionParams);
	}
};

/**
 * @class SegmentManager
 * @constructor
 * @param CloudHomeScreen cloudHomeScreen
 * @memberOf CloudHomeScreen
 */
var SegmentManager = function(cloudHomeScreen) {
	this.cloudHomeScreen = cloudHomeScreen;
	this.segmentList = null;
	this.initialize([]);
};

/**
 * @lends SegmentManager.prototype
 */
SegmentManager.prototype = {
	/**
	 * set 'segmentList' instance
	 * @function
	 * @param {Array} list
	 */
	setSegmentList : function(list) {
		this.segmentList = list;
	},

	/**
	 * get 'segmentList' instance
	 * @function
	 * @returns {Array} this.segmentList
	 */
	getSegmentList : function() {
		return this.segmentList;
	},
	
	/**
	 * get 'homeInfo' instance
	 * @function
	 * @returns {Array} this.homeInfo
	 */
	getHomeInfo : function() {
		return this.homeInfo;
	},

	/**
	 * initialize SegmentManager
	 * @function
	 * @param order
	 */
	initialize : function(orders) {
		delete this.homeInfo;
		this.homeInfo = {};
		
		for (var i=0, segmentCount=orders.length ; i<segmentCount ; ++i) {
			this.addHomeInfo(orders[i]);
		}
	},

	/**
	 * save one home information in SegmentManager
	 * @function
	 * @param {Object} info
	 */
	addHomeInfo : function(info) {
		var homeId = info.homeId;
		
		if (homeId && (homeId != "")) {
			this.homeInfo[info.homeId] = {
				layout : info.layout,
				option : {},
				webclipIncluded : this.getWebclipListFromLayout(info.layout),
				objList : {},
				loaded : {}
			};
		}
	},

	/**
	 * get webclip list from parameter 'layout'
	 * @function
	 * @param {Array} layout
	 * @returns {Array} webclip_list
	 */
	getWebclipListFromLayout : function(layout) {
		var result = [];
		
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			var sgmtId = layout[i];
			
			if (sgmtId.indexOf("wc") != -1) {
				result.push(sgmtId);
			}
		}

		return result;
	},

	getInitSegmentOption : function(sgmtId) {
		return this.getNewSegmentObject(sgmtId).getInitOption();
	},
	
	getInitSegmentOptions : function(homeId) {
		var optionInfo = [],
			layout = this.getLayout(homeId);
		
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			var sgmtId = layout[i],
				info = {
					homeId : homeId,
					sgmtId : sgmtId,
					options : this.getInitSegmentOption(sgmtId),
					isInitOption : true
				};
			
			optionInfo.push(info);
		}
		
		return optionInfo;
	},
	
	/**
	 * set segment options with default value
	 * @function
	 */
	initSegmentOptions : function(homeId) {
		var layout = this.homeInfo[homeId].layout;
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			this.initSegmentOption(homeId, layout[i]);
		}
	},

	/**
	 * set segment option with its default value
	 * @function
	 * @param {String} homeId
	 * @param {String} sgmtId
	 */
	initSegmentOption : function(homeId, sgmtId) {
		var segmentObj = this.getNewSegmentObject(sgmtId);
		this.setSegmentOption(homeId, sgmtId, segmentObj.getInitOption(), true);
	},

	/**
	 * insert segment option value into chs_segment_option table
	 * @function
	 * @param {String} homeId
	 * @param {String} sgmtId
	 */
	insertSegmentOption : function(homeId, sgmtId) {
		var segmentManager = this,
			cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.getEventHandler();
		
		homeEventHandler.showStatusBar("Insert Segment Option...");
		if (homeEventHandler.checkOnLine()) {
			var option = JSON.stringify(this.homeInfo[homeId].option[sgmtId]);
			console.log("[updateSegmentOption] homeId : " + homeId + ", sgmtId : " + sgmtId + ", option : " + option);
			if (chsConstants.isCloudPhone) {
				var valueObject = new SyncManager.CHSSegmentOption();
				valueObject._options = option;
				valueObject._home_id = homeId;
				valueObject._sgmt_id = sgmtId;
				cloudHomeScreen.getSyncManager().insert(valueObject, function() {
					homeEventHandler.hideStatusBar();
				}, function(message) {
					homeEventHandler.showErrorMessage(message);
					homeEventHandler.hideStatusBar();
				}, false);
				
				cloudHomeScreen.updateLayout();
			} else {
				var url = "/aphone/chs/segmentOption/add",
					type = "POST",
					params = "options=" + encodeURIComponent(option) +
						"&homeId=" + encodeURIComponent(homeId) + "&sgmtId=" + encodeURIComponent(sgmtId) +
						"&layouts=" + encodeURIComponent(cloudHomeScreen.layoutStringify());
				
				if (chsConstants.workerExist) {
					var data = { url : url, type : type, data : params };
					homeEventHandler.executeWorker("insertSegmentOption", data, function(xhr) {
						segmentManager.insertSegmentOptionCallback(xhr);
					});
				} else {
					jQuery.ajax({
						url : url,
						type : type,
						data : params,
						complete : function(xhr) {
							if (xhr.readyState == 4) {
								segmentManager.insertSegmentOptionCallback(xhr);
							}
						}
					});
				}
			}
		}
	},
	
	insertSegmentOptionCallback : function(xhr) {
		var cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.getEventHandler();
		
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
					// success message
					console.log("CHS_SEGMENT_OPTION INSERT SUCCESS");
					homeEventHandler.hideStatusBar();
					
					// set local storage
					homeEventHandler.setLocalStorage("homeManagerInfo", cloudHomeScreen.layoutStringify());
					
					var segmentManagerInfo = this.getSegmentManagerInfo();
					homeEventHandler.setLocalStorage("segmentManagerInfo", JSON.stringify(segmentManagerInfo));
				} else {
					// error message
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
		} else {
			// error message
			homeEventHandler.showErrorMessage(response.message.text);
			homeEventHandler.hideStatusBar();
		}
	},

	/**
	 * update layouts in homeList instance
	 * <li>
	 * <p>layouts : [{
	 * 	homeId : "homeXXXXXXXXXXXXX",
	 * 	layout : [ ... ]
	 * }, ... {
	 * }]</p>
	 * </li>
	 * @function
	 * @param {Object} layouts
	 */
	updateLayoutInfo : function(layouts) {
		for (var i=0, segmentCount=layouts.length ; i<segmentCount ; ++i) {
			this.setLayout(layouts[i].homeId, layouts[i].layout);
			this.homeInfo[layouts[i].homeId].webclipIncluded = this.getWebclipListFromLayout(layouts[i].layout);
		}
	},

	/**
	 * update current home's layout
	 * @function
	 * @param {String} homeId
	 */
	updateLayout : function(homeId, update) {
		var layout = jQuery("#" + homeId + " > ul").sortable("toArray");
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			layout[i] = layout[i].replace(homeId, "");
		}
		
		// Get previous layout
		var previousLayout = this.getPreviousLayoutOfCurrentHome();
		if (previousLayout != layout.toString()) {
			this.setLayout(homeId, layout);
			this.homeInfo[homeId].webclipIncluded = this.getWebclipListFromLayout(layout);

			if (update) {
				this.cloudHomeScreen.updateLayout();		// done �꾨� �뚮쭔 update
			}
		}
	},

	/**
	 * set homeId's layout
	 * @function
	 * @param {String} homeId
	 * @param {Array} layout
	 */
	setLayout : function(homeId, layout) {
		this.homeInfo[homeId].layout = layout;
	},
	
	/**
	 * save current home's layout temporarily
	 * @function
	 */
	saveCurrentHomeLayout : function() {
		var homeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId();
		this.homeInfo[homeId].previousLayout = this.homeInfo[homeId].layout.toString();
	},
	
	/**
	 * get saved current home's layout
	 * @returns {String} previousLayout
	 */
	getPreviousLayoutOfCurrentHome : function() {
		var homeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId();
		return this.homeInfo[homeId].previousLayout;
	},

	/**
	 * add segment into current home
	 * @function
	 * @param {String} sgmtId
	 * @param {Object} option
	 */
	addSegment : function(sgmtId, option) {
		this.cloudHomeScreen.getEventHandler().showStatusBar("Add Segment...");
		var homeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId();
		
		// save current home's layout
		this.saveCurrentHomeLayout();

		// update instance value
		if (option == null) {
//			this.initSegmentOption(homeId, sgmtId);
//			option = this.getSegmentOption(homeId, sgmtId);
			option = this.getInitSegmentOption(sgmtId);
		} else {
//			this.setSegmentOption(homeId, sgmtId, option, true);
			this.setSegmentOption(homeId, sgmtId, option, false);
		}

		// create segment
		this.createSegment(homeId, sgmtId);
		
		// change the width of screen class
		var pageWidth = window.innerWidth;
		jQuery(".segment_container li > .screen").css("width", pageWidth + "px");

		// load segment
		this.loadSegment(homeId, sgmtId, option);

		// update layout
		this.updateLayout(homeId, false);
		if (sgmtId.indexOf("wc") == -1) {
			this.setSegmentOption(homeId, sgmtId, option, true);
		}

		// hide delete button if current mode isn't 'edit'
		if (this.cloudHomeScreen.getEventHandler().getCurrentMode().indexOf("edit") == -1) {
			jQuery("#" + homeId + " #" + homeId + sgmtId + " .icon-delete").hide();
		} else {
			// add change class
			this.cloudHomeScreen.getHomeManager().startSegmentEditMode();
		}
	},

	/**
	 * segment瑜���젣�쒕떎.
	 * @function
	 * @param homeId
	 * @param sgmtId
	 */
	deleteSegment : function(homeId, sgmtId) {
		var segmentManager = this;
		
		// save current home's layout
		this.saveCurrentHomeLayout();
		
		jQuery("#" + homeId + " #" + homeId + sgmtId).fadeOut("fast", function() {
			jQuery(this).remove();		// remove segment
			
			if (sgmtId.indexOf("wc") == -1) {
				segmentManager.deleteSegmentInfo(homeId, sgmtId);		// update instance value
				segmentManager.updateLayout(homeId, false);		// update segment info
			} else {
				segmentManager.updateLayout(homeId, true);		// update segment info
			}
			
			// delete iscroll
			segmentManager.cloudHomeScreen.getEventHandler().removeIScroll(homeId + sgmtId + "Section");
		});
	},

	/**
	 * homeInfo�먯꽌 homeId���랁븳 sgmtId����븳 �뺣낫瑜���젣, DB��諛섏쁺�쒕떎.
	 * @function
	 * @param homeId
	 * @param sgmtId
	 */
	deleteSegmentInfo : function(homeId, sgmtId) {
		var layout = this.homeInfo[homeId].layout;
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			if (layout[i] == sgmtId) {
				this.homeInfo[homeId].layout.splice(i, 1);
				delete this.homeInfo[homeId].option[sgmtId];
				this.deleteSegmentObject(homeId, sgmtId);
				break;
			}
		}

		this.deleteSegmentOption(homeId, sgmtId);
	},
	
	deleteSegmentObject : function(homeId, sgmtId) {
		var segmentObj = this.homeInfo[homeId].objList[sgmtId];
		if (segmentObj && segmentObj.onRemoved && (typeof(segmentObj.onRemoved) == "function")) {
			segmentObj.onRemoved();
		}
		delete this.homeInfo[homeId].objList[sgmtId];
	},

	/**
	 * @function
	 * @param homeId
	 * @param sgmtId
	 */
	deleteSegmentOption : function(homeId, sgmtId) {
		var segmentManager = this,
			cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.getEventHandler();
		
		if (homeEventHandler.checkOnLine()) {
			homeEventHandler.showStatusBar("Delete Segment Option...");
			console.log("[deleteSegmentOption] homeId : " + homeId + ", sgmtId : " + sgmtId);
			if (chsConstants.isCloudPhone) {
				var valueObject = new SyncManager.CHSSegmentOption();
				valueObject._home_id = homeId;
				valueObject._sgmt_id = sgmtId;
				cloudHomeScreen.getSyncManager().remove(valueObject, function() {
					homeEventHandler.hideStatusBar();
				}, function(message) {
					homeEventHandler.showErrorMessage(message);
					homeEventHandler.hideStatusBar();
				}, false);
				
				cloudHomeScreen.updateLayout();
			} else {
				var url = "/aphone/chs/segmentOption/delete",
					type = "POST",
					params = "homeId=" + encodeURIComponent(homeId) + "&sgmtId=" + encodeURIComponent(sgmtId) +
						"&layouts=" + encodeURIComponent(cloudHomeScreen.layoutStringify());
				
				if (chsConstants.workerExist) {
					var data = { url : url, type : type, data : params };
					homeEventHandler.executeWorker("deleteSegmentOption", data, function(xhr) {
						segmentManager.deleteSegmentOptionCallback(xhr);
					});
				} else {
					jQuery.ajax({
						url : url,
						type : type,
						data : params,
						complete : function(xhr) {
							if (xhr.readyState == 4) {
								segmentManager.deleteSegmentOptionCallback(xhr);
							}
						}
					});
				}
			}
		}
	},
	
	deleteSegmentOptionCallback : function(xhr) {
		var cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.getEventHandler();
		
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
					// success message
					console.log("CHS_SEGMENT_OPTION DELETE SUCCESS");
					homeEventHandler.hideStatusBar();
					
					// set local storage
					homeEventHandler.setLocalStorage("homeManagerInfo", cloudHomeScreen.layoutStringify());
					
					var segmentManagerInfo = this.getSegmentManagerInfo();
					homeEventHandler.setLocalStorage("segmentManagerInfo", JSON.stringify(segmentManagerInfo));
				} else {
					// error message
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
		}
	},
	
	/**
	 * 蹂�꼍��segment option �뺣낫瑜�諛섏쁺�쒕떎.
	 * @param homeId
	 * @param sgmtId
	 * @param option
	 */
	updateSegment : function(segmentObj) {
		var prevOption = segmentObj.getPrevOption();
		
		var homeId = segmentObj.getHomeId();
		var sgmtId = segmentObj.getSegmentId();
		var option = segmentObj.getOption();
		if (prevOption != JSON.stringify(option)) {
			// update segment_option info
			this.setSegmentOption(homeId, sgmtId, option, false);
			
			// update segment object
			this.updateSegmentObject(homeId, sgmtId, option);
			
			// reload segment
			this.loadSegment(homeId, sgmtId, option);
			this.cloudHomeScreen.getHomeManager().startSegmentEditMode();
			
			// update segment option on DB
			this.updateSegmentOption(homeId, sgmtId);
		}
	},
	
	/**
	 * DB��segment option �뺣낫瑜���옣�쒕떎.
	 * @function
	 * @param homeId
	 * @param sgmtId
	 */
	updateSegmentOption : function(homeId, sgmtId) {
		var segmentManager = this,
			cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.getEventHandler();
		
		cloudHomeScreen.homeEventHandler.showStatusBar("Update Segment Option...");
		// �뺣낫 �낅뜲�댄듃 ��!
		if (homeEventHandler.checkOnLine()) {
			var option = JSON.stringify(this.homeInfo[homeId].option[sgmtId]);
			console.log("[updateSegmentOption] homeId : " + homeId + ", sgmtId : " + sgmtId + ", option : " + option);
			if (chsConstants.isCloudPhone) {
				var valueObject = new SyncManager.CHSSegmentOption();
				valueObject._options = option;
				valueObject._home_id = homeId;
				valueObject._sgmt_id = sgmtId;
				cloudHomeScreen.getSyncManager().update(valueObject, function() {
					homeEventHandler.hideStatusBar();
				}, function(message) {
					homeEventHandler.showErrorMessage(message);
					homeEventHandler.hideStatusBar();
				}, false);
			} else {
				var url = "/aphone/chs/segmentOption/update",
					type = "POST",
					params = "homeId=" + encodeURIComponent(homeId) + "&sgmtId=" + encodeURIComponent(sgmtId) +
						"&options=" + encodeURIComponent(option);
				
				if (chsConstants.workerExist) {
					var data = { url : url, type : type, data : params };
					homeEventHandler.executeWorker("updateSegmentOption", data, function(xhr) {
						segmentManager.updateSegmentOptionCallback(xhr);
					});
				} else {
					jQuery.ajax({
						url : url,
						type : type,
						data : params,
						complete : function(xhr) {
							if (xhr.readyState == 4) {
								segmentManager.updateSegmentOptionCallback(xhr);
							}
						}
					});
				}
			}
			
			// set local storage
			var segmentManagerInfo = segmentManager.getSegmentManagerInfo();
			homeEventHandler.setLocalStorage("segmentManagerInfo", JSON.stringify(segmentManagerInfo));
		} else {
			console.error("can't update chs_segment_option. (offline)");
		}
	},
	
	updateSegmentOptionCallback : function(xhr) {
		var homeEventHandler = this.cloudHomeScreen.getEventHandler();
		
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
					console.log("CHS_SEGMENT_OPTION UPDATE SUCCESS");
					homeEventHandler.hideStatusBar();
				} else {
					// error message
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
		}
	},

	/**
	 * segmentList�먯꽌 fncName���대떦�섎뒗 segment��id瑜�媛�졇�⑤떎.
	 * @param fncName
	 * @returns
	 */
	getSegmentId : function(fncName) {
		for (var i=0, segmentCount=this.segmentList.length ; i<segmentCount ; ++i) {
			if (this.segmentList[i].fncName == fncName) {
				return this.segmentList[i].id;
			}
		}
		
		return null;
	},
	
	/**
	 * segmentList�먯꽌 sgmtId���대떦�섎뒗 segment���대쫫��媛�졇�⑤떎.
	 * @param sgmtId
	 * @returns
	 */
	getSegmentName : function(sgmtId) {
		if (sgmtId.indexOf("wc") != -1) {
			return "web clips";
		}

		for (var i=0, segmentCount=this.segmentList.length ; i<segmentCount ; ++i) {
			if (this.segmentList[i].id == sgmtId) {
				return this.segmentList[i].name;
			}
		}

		return "User Defined App";
	},

	/**
	 * segmentList�먯꽌 sgmtId���대떦�섎뒗 segment��type��媛�졇�⑤떎.
	 * @function
	 * @param sgmtId
	 * @returns
	 */
	getSegmentType : function(sgmtId) {
		if (sgmtId.indexOf("wc") != -1) {
			return "webclip";
		}

		for (var i=0, segmentCount=this.segmentList.length ; i<segmentCount ; ++i) {
			if (this.segmentList[i].id == sgmtId) {
				return this.segmentList[i].fncName;
			}
		}

		return "userDefined";
	},
	
	/**
	 * segmentList�먯꽌 sgmtId���대떦�섎뒗 segment���ㅻ챸 �뺣낫瑜�媛�졇�⑤떎.
	 * @param sgmtId
	 * @returns
	 */
	getSegmentDescription : function(sgmtId) {
		for (var i=0 ; i<this.segmentList.length ; ++i) {
			if (this.segmentList[i].id == sgmtId) {
				return this.segmentList[i].description;
			}
		}
	},

	/**
	 * @function
	 * @param homeId
	 * @returns
	 */
	getLayout : function(homeId) {
		if (this.homeInfo[homeId]) {
			return this.homeInfo[homeId].layout;	
		}
		
		return [];
	},
	
	getCurrentHomeLayout : function() {
		var homeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId();
		return this.getLayout(homeId);
	},

	/**
	 * homeInfo��segment���듭뀡 �뺣낫瑜���옣�쒕떎.
	 * @function
	 * @param homeId
	 * @param sgmtId
	 * @param option
	 */
	setSegmentOption : function(homeId, sgmtId, option, isInitOption) {
		if (this.homeInfo[homeId]) {
			this.homeInfo[homeId].option[sgmtId] = option;
			var loadType = this.cloudHomeScreen.getEventHandler().loadType;
			if ((loadType != "cache") && isInitOption) {
				this.insertSegmentOption(homeId, sgmtId);
			}
		}
	},
	
	setSegmentOptions : function(optionInfo) {
		for (var i=0, optionCount=optionInfo.length ; i<optionCount ; ++i) {
			var item = optionInfo[i];
			this.setSegmentOption(item.homeId, item.sgmtId, item.options, item.isInitOption);
		}
	},
	
	/**
	 * homeInfo�먯꽌 segment���듭뀡 �뺣낫瑜�媛�졇�⑤떎.
	 * @function
	 * @param homeId
	 * @param sgmtId
	 * @returns
	 */
	getSegmentOption : function(homeId, sgmtId) {
		if (sgmtId.indexOf("wc") == -1) {
			if (this.homeInfo[homeId]) {
				return this.homeInfo[homeId].option[sgmtId];
			} else {
				return null;
			}
		} else {
			return this.cloudHomeScreen.getWebclipManager().getOption(sgmtId);
		}
	},

	/**
	 * @function
	 * @param homeId
	 * @param sgmtId
	 */
	createSegment : function(homeId, sgmtId) {
		var selector = "#" + homeId + " #" + homeId + sgmtId;
		if (jQuery(selector).size() == 0) {
			var segmentName = this.getSegmentName(sgmtId).toLowerCase();
			var fncName = this.getSegmentType(sgmtId);
			var innerHTML = "<li id=\"" + homeId + sgmtId + "\">" +
								"<div class=\"screen\">" +
									"<div class=\"segment\">" +
										"<h2>" + segmentName + "</h2>" +
										"<section id=\"" + homeId + sgmtId + "Section\" class=\"" + fncName + "\">" +
											"<div class=\"moving_area\" style=\"height: 100%;\"></div>" +
											"<div class=\"icon-delete\"></div>" +
										"</section><!-- " + fncName + " -->" +
										"<div class=\"segment_cover\"></div>" +
									"</div>" +
								"</div>" +
							"</li>";
			jQuery("#" + homeId + " > ul").append(innerHTML);
			jQuery(selector + " section").append(this.getSlideDiv(homeId, sgmtId));
			
			jQuery(selector + " .icon-delete").css("cursor", "pointer").unbind("click").bind("click", {
				segmentManager : this,
				homeId : homeId,
				sgmtId : sgmtId
			}, this.cloudHomeScreen.getEventHandler().onSegmentDeleted);
		}
	},

	getSlideDiv : function(homeId, sgmtId) {
		var innerHTML = "<div class=\"arrow_container\">" + 
							"<a id=\"" + homeId + sgmtId + "_slidePrev\" class=\"arrow-left\"></a>" +
							"<a id=\"" + homeId + sgmtId + "_slideNext\" class=\"arrow-right\"></a>" +
						"</div>";

		return innerHTML;
	},

	loadUnloadedSegments : function(homeId) {
		var homeEventHandler = this.cloudHomeScreen.getEventHandler(),
			thisHome = this.homeInfo[homeId];
		
		for (var i=0, segmentCount=thisHome.layout.length ; i<segmentCount ; ++i) {
			var sgmtId = thisHome.layout[i];
			homeEventHandler.showStatusBar("Load unloaded segment, " + this.getSegmentName(sgmtId));
			if (!thisHome.loaded[sgmtId]) {
				var option = this.getSegmentOption(homeId, sgmtId);
				
				this.loadSegment(homeId, sgmtId, option);
			}
		}
		
		homeEventHandler.hideStatusBar();
	},
	
	removeUnusedSegments : function(homeId) {
		var segmentList = jQuery("#" + homeId + " > ul > li"),
			length = segmentList.length;
		
		for (var i=0 ; i<length ; ++i) {
			var segment = segmentList.get(i),
				sgmtId = jQuery(segment).attr("id").replace(homeId, "");
			
			if (!this.homeInfo[homeId].objList.hasOwnProperty(sgmtId) && (sgmtId != "SGMT_0000000000001")) {
				console.warn("unused segment : homeId - " + homeId + ", sgmtId - " + sgmtId);
				this.deleteSegment(homeId, sgmtId);
			}
		}
	},
	
	/**
	 * @function
	 * @param homeId
	 */
	loadSegments : function(homeId) {
		var thisHome = this.homeInfo[homeId];
		for (var i=0, segmentCount=thisHome.layout.length ; i<segmentCount ; ++i) {
			var sgmtId = thisHome.layout[i],
				option = this.getSegmentOption(homeId, sgmtId);
			this.loadSegment(homeId, sgmtId, option);
		}
	},

	/**
	 * @function
	 * @param homeId
	 * @param sgmtId
	 * @param option
	 */
	loadSegment : function(homeId, sgmtId, option) {
		if (jQuery("#" + homeId + " #" + homeId + sgmtId).size() > 0) {
			pu.startMilestone("display, segment, " + this.getSegmentName(sgmtId));
			var segmentObj = this.getSegmentObject(homeId, sgmtId);
			if (option == null) {
				if (sgmtId.indexOf("wc") == -1) {
					this.initSegmentOption(homeId, sgmtId);
					option = this.getSegmentOption(homeId, sgmtId);
				} else {
					option = this.cloudHomeScreen.getWebclipManager().getOption(sgmtId);
				}
			}
			
			if (segmentObj instanceof WebclipSegment) {
				segmentObj.load(homeId, sgmtId, option, true);
			} else {
				var loadType = this.cloudHomeScreen.getEventHandler().loadType;
				segmentObj.load(homeId, sgmtId, option, loadType);
			}
			
			if (loadType != "cache") {
				this.homeInfo[homeId].loaded[sgmtId] = true;
			}
			
			// save object
			this.setSegmentObject(homeId, sgmtId, segmentObj);
			pu.finishMilestone("display, segment, " + this.getSegmentName(sgmtId));
			
			this.cloudHomeScreen.getEventHandler().increaseSegmentLoadCount();
		}
	},

	/**
	 * @function
	 * @param homeId
	 */
	deleteHomeInfo : function(homeId) {
		delete this.homeInfo[homeId];
	},
	
	getPopupInfo : function(type, params) {
		var cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.getEventHandler(),
			homeManager = cloudHomeScreen.getHomeManager(),
			currentHomeId = homeManager.getCurrentHomeId(),
			title = null,
			list = null,
			buttons = null,
			onBackgroundClick = {
				object : this.cloudHomeScreen,
				method : cloudHomeScreen.setHash,
				params : ["editHome"]
				/*params : {
					cloudHomeScreen : this.cloudHomeScreen
				},
				handler : function(event) {
					var cloudHomeScreen = event.data.cloudHomeScreen;
					var hash = "editHome";
					cloudHomeScreen.setHash(hash);
				}*/
			};
		
		if (type == "add segment") {
			title = "Add to Home screen";
			list = {
				left : "none",		// thumbnail, icon, none
				middle : 1,			// 1, 2, 3 (1-line, 2-lines, 3-lines)
				right : "none",		// radio, checkbox, onoff, none
				data : []
			};
			var addableSegment = this.getAddableSegmentList(),
				addableCategory = this.getAddableNewsCategoryList();
			for (var i=0, count=addableSegment.length ; i<count ; ++i) {
				// �붿씠��異붽����댁뒪 移댄뀒怨좊━媛��놁쓣 寃쎌슦 news���쒖쇅�쒕떎.
				if ((addableSegment[i].name == "News") && (addableCategory.length == 0)) {
					continue;
				}
				var data = {
					line1 : addableSegment[i].name,
					events : [{
						type : "tap",
						params : {
							cloudHomeScreen : this.cloudHomeScreen,
							sgmtId : addableSegment[i].id
						},
						handler : this.cloudHomeScreen.addSegment
					}]
				};
				list.data.push(data);
			}
		}
		// Popup Type : edit detail
		else if (type == "topstory") {
			if (params) {
				var segmentObj = params.segmentObj,
					homeId = segmentObj.getHomeId(),
					sgmtId = segmentObj.getSegmentId();
				
				this.setSegmentObject(homeId, sgmtId, segmentObj);		// save segment object
				
				title = "Top Story items";
				list = {
					left : "none",
					middle : 1,
					right : "checkbox",
					data : [],
					checkbox : {
						required : true
					}
				};
				var items = segmentObj.getTopstoryList();
				for (var i=0, optionCount=items.length ; i<optionCount ; ++i) {
					var data = {
						line1 : items[i].name,
						checkbox : {
							id : items[i].id,
							checked : items[i].useYn
						}
					};
					list.data.push(data);
				}
				this.popupButtonLeftHandler = function(homeId, sgmtId) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.segmentManager.getSegmentObject(homeId, sgmtId),
						checkboxInfo = cloudHomeScreen.homeEventHandler.getPopup().getCheckboxInfo();
					if (checkboxInfo) {
						segmentObj.updateOption(checkboxInfo);
					}
					
					cloudHomeScreen.segmentManager.updateSegment(segmentObj);
					
					cloudHomeScreen.setHash("editHome");
				};
				buttons = [{
					value : "OK",
					href : "chs.segmentManager.popupButtonLeftHandler('" + homeId + "', '" + sgmtId + "')"
				}, {
					value : "Cancel",
					href : "chs.setHash('editHome')"
				}];
			}
		} else if (type == "news") {
			title = "News category";
			var addableCategory = this.getAddableNewsCategoryList();
			list = {
				left : "none",		// thumbnail, icon, none
				middle : 1,			// 1, 2, 3 (1-line, 2-lines, 3-lines)
				right : "none",		// radio, checkbox, onoff, none
				data : []
			};
			for (var i=0, count=addableCategory.length ; i<count ; ++i) {
				var data = {
					line1 : addableCategory[i].name,
					events : [{
						type : "tap",
						params : {
							cloudHomeScreen : this.cloudHomeScreen,
							sgmtId : addableCategory[i].id
						},
						handler : function(event) {
							var cloudHomeScreen = event.data.cloudHomeScreen;
							var sgmtId = event.data.sgmtId;
							
							cloudHomeScreen.segmentManager.addSegment(sgmtId);
							
							// finish add segment mode
							var hash = "editHome";
							cloudHomeScreen.setHash(hash);
						}
					}]
				};
				list.data.push(data);
			}
		} else if (type == "snsfeeds") {
			if (params) {
				var segmentObj = params.segmentObj;
				if (segmentObj == null) {
					segmentObj = this.getNewSegmentObject(params.sgmtId);
					segmentObj.setHomeId(this.cloudHomeScreen.getHomeManager().getCurrentHomeId());
					segmentObj.setSegmentId(params.sgmtId);
					segmentObj.initSegmentOption();
				}
				var homeId = segmentObj.getHomeId(),
					sgmtId = segmentObj.getSegmentId();
				this.setSegmentObject(homeId, sgmtId, segmentObj);		// save segment object	
				
				title = "SNS feeds";
				list = {
					left : "none",
					middle : 1,
					right : "checkbox",
					data : [],
					checkbox : {
						required : true
					}
				};
				var snsSource = segmentObj.getSnsList();
				for (var i=0, count=snsSource.length ; i<count ; ++i) {
					var data = {
						line1 : snsSource[i].name,
						checkbox : {
							id : snsSource[i].id,
							checked : snsSource[i].useYn
						}
					};
					list.data.push(data);
				}
				this.popupButtonLeftHandler = function(homeId, sgmtId) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
						checkboxInfo = cloudHomeScreen.getEventHandler().getPopup().getCheckboxInfo();
					if (checkboxInfo && (checkboxInfo.length > 0)) {
						segmentObj.updateOption(checkboxInfo);
						
						// reload or add segment
						var option = segmentObj.getOption();
						if (jQuery("#" + homeId + " #" + homeId + sgmtId).length == 0) {
							cloudHomeScreen.getSegmentManager().addSegment(sgmtId, option);
						} else {
							// update segment
							cloudHomeScreen.getSegmentManager().updateSegment(segmentObj);
						}
						
						cloudHomeScreen.setHash("editHome");
					}
				};
				buttons = [{
					value : "OK",
					href : "chs.segmentManager.popupButtonLeftHandler('" + homeId + "', '" + sgmtId + "')"
				}, {
					value : "Cancel",
					href : "chs.setHash('editHome')"
				}];
			}
		} else if (type == "gallery add photos from") {
			if (params) {
				var segmentObj = params.segmentObj;
				if (segmentObj == null) {
					segmentObj = this.getNewSegmentObject(params.sgmtId);
					segmentObj.setHomeId(this.cloudHomeScreen.getHomeManager().getCurrentHomeId());
					segmentObj.setSegmentId(params.sgmtId);
					segmentObj.initGalleryInfo();
				}
				
				title = "Add Photos from";
				var gallerySource = segmentObj.getGallerySource();
				list = {
					left : "none",		// thumbnail, icon, none
					middle : 1,			// 1, 2, 3 (1-line, 2-lines, 3-lines)
					right : "none",		// radio, checkbox, onoff, none
					data : []
				};
				for (var i=0, count=gallerySource.length ; i<count ; ++i) {
					var data = {
						line1 : gallerySource[i],
						events : [{
							type : "tap",
							params : {
								cloudHomeScreen : this.cloudHomeScreen,
								segmentObj : segmentObj,
								source : gallerySource[i]
							},
							handler : function(event) {
								var cloudHomeScreen = event.data.cloudHomeScreen;
								var segmentObj = event.data.segmentObj;
								var source = event.data.source;
								
								if (source == "sns") {
									cloudHomeScreen.showPopup(cloudHomeScreen.getSegmentManager().getPopupInfo("gallery select folder", { source : source, segmentObj : segmentObj }));
								} else if (source == "mycloud") {
									segmentObj.updateFolderUseYn({ id : "gallery_mycloud", useYn : true }, source);
									
									cloudHomeScreen.showPopup(cloudHomeScreen.getSegmentManager().getPopupInfo("gallery added photos", { segmentObj : segmentObj }));
								}
							}
						}]
					};
					list.data.push(data);
				}
			}
		} else if (type == "gallery select folder") {
			if (params) {
				var segmentObj = params.segmentObj,
					source = params.source,
					homeId = segmentObj.getHomeId(),
					sgmtId = segmentObj.getSegmentId();
				this.setSegmentObject(homeId, sgmtId, segmentObj);
				
				title = "Select folder";
				list = {
						left : "none",		// thumbnail, icon, none
						middle : 1,			// 1, 2, 3 (1-line, 2-lines, 3-lines)
						right : "checkbox",		// radio, checkbox, onoff, none
						data : [],
						checkbox : {
							required : false,
							removable : false
						}
				};
				segmentObj.initGalleryInfo();
				var folderList = segmentObj.getFolderList(source);
				for (var i=0, count=folderList.length ; i<count ; ++i) {
					var data = {
							line1 : folderList[i].name,
							checkbox : {
								id : folderList[i].id,
								checked : folderList[i].useYn
							}
					};
					list.data.push(data);
				}
				this.popupButtonLeftHandler = function(homeId, sgmtId, source) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
						checkboxInfo = cloudHomeScreen.getEventHandler().getPopup().getCheckboxInfo();
					if (checkboxInfo && (checkboxInfo.length > 0)) {
						segmentObj.updateFolderUseYn(checkboxInfo, source);
					}
					
					cloudHomeScreen.showPopup(cloudHomeScreen.getSegmentManager().getPopupInfo("gallery added photos", { segmentObj : segmentObj }));
				};
				this.popupButtonRightHandler = function(homeId, sgmtId) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId);
					
					cloudHomeScreen.showPopup(cloudHomeScreen.getSegmentManager().getPopupInfo("gallery added photos", { segmentObj : segmentObj }));
				};
				buttons = [{
					value : "OK",
					href : "chs.segmentManager.popupButtonLeftHandler('" + homeId + "', '" + sgmtId + "', '" + source + "')"
				}, {
					value : "Cancel",
					href : "chs.segmentManager.popupButtonRightHandler('" + homeId + "', '" + sgmtId + "')"
				}];
			}
		} else if (type == "gallery added photos") {
			if (params) {
				var segmentObj = params.segmentObj,
					homeId = segmentObj.getHomeId(),
					sgmtId = segmentObj.getSegmentId();
				this.setSegmentObject(homeId, sgmtId, segmentObj);
				
				title = "Added Photos";
				list = {
						left : "none",			// thumbnail, icon, none
						middle : 1,				// 1, 2, 3 (1-line, 2-lines, 3-lines)
						right : "minus",		// radio, checkbox, onoff, none
						data : []
				};
				var usedSource = segmentObj.getUsedFolderList();
				for (var i=0, count=usedSource.length ; i<count ; ++i) {
					var data = {
						line1 : usedSource[i].name,
						minus : {
							id : usedSource[i].id
						}
					};
					list.data.push(data);
				}
				this.popupButtonLeftHandler = function(homeId, sgmtId) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
						dataInfo = cloudHomeScreen.getEventHandler().getPopup().getDataInfo();
					if (dataInfo) {
						segmentObj.updateOptionList(dataInfo);
					}
					
					cloudHomeScreen.showPopup(cloudHomeScreen.getSegmentManager().getPopupInfo("gallery add photos from", { segmentObj : segmentObj }));
				};
				this.popupButtonRightHandler = function(homeId, sgmtId) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
						dataInfo = cloudHomeScreen.getEventHandler().getPopup().getDataInfo();
					if (dataInfo && (dataInfo.length > 0)) {
						segmentObj.updateOptionList(dataInfo);
						
						var option = segmentObj.getOption();
						if (jQuery("#" + homeId + " #" + homeId + sgmtId).length == 0) {
							cloudHomeScreen.getSegmentManager().setSegmentObject(homeId, sgmtId, segmentObj);
							cloudHomeScreen.getSegmentManager().addSegment(sgmtId, option);
						} else {
							// update segment
							cloudHomeScreen.getSegmentManager().updateSegment(segmentObj);
						}
					}
					
					cloudHomeScreen.setHash("editHome");
				};
				buttons = [{
					value : "Add photos",
					href : "chs.segmentManager.popupButtonLeftHandler('" + homeId + "', '" + sgmtId + "')"
				}, {
					value : "OK",
					href : "chs.segmentManager.popupButtonRightHandler('" + homeId + "', '" + sgmtId + "')"
				}];
			}
		} else if (type == "stock") {
			if (params) {
				var segmentObj = params.segmentObj,
					homeId = segmentObj.getHomeId(),
					sgmtId = segmentObj.getSegmentId();
				this.setSegmentObject(homeId, sgmtId, segmentObj);
				
				title = "Added Stocks";
				list = {
						left : "none",
						middle : 1,
						right : "minus",
						data : []
				};
				var stockList = segmentObj.getStockList();
				for (var i=0, count=stockList.length ; i<count ; ++i) {
					var data = {
						line1 : stockList[i].name,
						minus : {
							id : stockList[i].id
						}
					};
					list.data.push(data);
				}
				this.popupButtonLeftHandler = function(homeId, sgmtId) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
						dataInfo = cloudHomeScreen.getEventHandler().getPopup().getDataInfo();
					if (dataInfo) {
						segmentObj.updateOptionList(dataInfo);
					}
					
					var hash = "optionSearch",
						actionParams = segmentObj;
					cloudHomeScreen.setHash(hash, actionParams);
				};
				this.popupButtonRightHandler = function(homeId, sgmtId) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
						dataInfo = cloudHomeScreen.getEventHandler().getPopup().getDataInfo();
					if (dataInfo && (dataInfo.length > 0)) {
						segmentObj.updateOptionList(dataInfo);
						
						// reload segment
						var option = segmentObj.getOption();
						if (option.length > 0) {
							if (jQuery("#" + homeId + " #" + homeId + sgmtId).length == 0) {
								cloudHomeScreen.getSegmentManager().setSegmentObject(homeId, sgmtId, segmentObj);
								cloudHomeScreen.getSegmentManager().addSegment(sgmtId, option);
							} else {
								// update segment
								cloudHomeScreen.segmentManager.updateSegment(segmentObj);
							}
						} else {
							// delete this segment because it contains no contents.
//							cloudHomeScreen.getEventHandler().inCaseOfNoContents(sgmtId);
						}
					}
					
					cloudHomeScreen.setHash("editHome");
				};
				buttons = [{
					value : "Add stocks",
					href : "chs.segmentManager.popupButtonLeftHandler('" + homeId + "', '" + sgmtId + "')"
				}, {
					value : "OK",
					href : "chs.segmentManager.popupButtonRightHandler('" + homeId + "', '" + sgmtId + "')"
				}];
			}
		} else if (type == "weather") {
			if (params) {
				var segmentObj = params.segmentObj,
					homeId = segmentObj.getHomeId(),
					sgmtId = segmentObj.getSegmentId();
				this.setSegmentObject(homeId, sgmtId, segmentObj);
				
				title = "Added Locations";
				list = {
						left : "none",
						middle : 1,
						right : "minus",
						data : []
				};
				var locationList = segmentObj.getLocationList();
				for (var i=0, count=locationList.length ; i<count ; ++i) {
					var data = {
						line1 : locationList[i].name,
						minus : {
							id : locationList[i].id
						}
					};
					list.data.push(data);
				}
				this.popupButtonLeftHandler = function(homeId, sgmtId) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
						dataInfo = cloudHomeScreen.getEventHandler().getPopup().getDataInfo();
					if (dataInfo) {
						segmentObj.updateOptionList(dataInfo);
					}
					
					var hash = "optionSearch",
						actionParams = segmentObj;
					cloudHomeScreen.setHash(hash, actionParams);
				};
				this.popupButtonRightHandler = function(homeId, sgmtId) {
					var cloudHomeScreen = chs,
						segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
						dataInfo = cloudHomeScreen.getEventHandler().getPopup().getDataInfo();
					if (dataInfo && (dataInfo.length > 0)) {
						segmentObj.updateOptionList(dataInfo);
						
						var option = segmentObj.getOption();
						if (option.length > 0) {
							if (jQuery("#" + homeId + " #" + homeId + sgmtId).length == 0) {
								cloudHomeScreen.segmentManager.setSegmentObject(homeId, sgmtId, segmentObj);
								cloudHomeScreen.segmentManager.addSegment(sgmtId, option);
							} else {
								// update segment
								cloudHomeScreen.segmentManager.updateSegment(segmentObj);
							}
						} else {
							// delete this segment because it contains no contents.
//							cloudHomeScreen.getEventHandler().inCaseOfNoContents(sgmtId);
						}
					}
					
					cloudHomeScreen.setHash("editHome");
				};
				buttons = [{
					value : "Add cities",
					href : "chs.segmentManager.popupButtonLeftHandler('" + homeId + "', '" + sgmtId + "')"
				}, {
					value : "OK",
					href : "chs.segmentManager.popupButtonRightHandler('" + homeId + "', '" + sgmtId + "')"
				}];
			}
		}
		
		return { title : title, list : list, buttons : buttons, onBackgroundClick : onBackgroundClick };
	},
	
	getAddableSegmentList : function() {
		var currentHomeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId();
		var list = new Array();
		for (var i=0, segmentCount=this.segmentList.length ; i<segmentCount ; ++i) {
			if (this.segmentList[i].id.indexOf("NEWS") == -1) {
				if (jQuery("#" + currentHomeId + " #" + currentHomeId + this.segmentList[i].id).length == 0) {
					list.push({ id : this.segmentList[i].id, name : this.segmentList[i].name });
				}
			}
		}
		
		return list;
	},
	
	getAddableNewsCategoryList : function() {
		var currentHomeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId();
		var list = new Array();
		for (var i=0, segmentCount=this.segmentList.length ; i<segmentCount ; ++i) {
//			if (this.segmentList[i].id.indexOf("AP") != -1) {
			if (this.segmentList[i].id.indexOf("YH") != -1) {
				if (jQuery("#" + currentHomeId + " #" + currentHomeId + this.segmentList[i].id).length == 0) {
					list.push({ id : this.segmentList[i].id, name : this.segmentList[i].name });
				}
			}
		}
		
		return list;
	},
	
	getSearchListInfo : function(segmentObj) {
		var placeholder = null,
			list = null,
			buttons = null,
			homeId = segmentObj.getHomeId(),
			sgmtId = segmentObj.getSegmentId(),
			type = segmentObj.getSegmentType();
		this.setSegmentObject(homeId, sgmtId, segmentObj);
		if (type == "contacts") {
			placeholder = "Search Contacts";
			var contactInfo = segmentObj.getContactInfo(),
				contactListLoaded = segmentObj.contactListLoaded;
			if (contactListLoaded) {
				list = {
						left : "thumbnail",
						middle : 1,
						right : "checkbox",
						data : [],
						checkbox : {
							required : false,
							removable : false
						}
				};
				for (var contactId in contactInfo) {
					if (contactInfo.hasOwnProperty(contactId)) {
						var contact = contactInfo[contactId];
						var data = {
							thumbnail : contact.value.picture,
							line1 : ((contact.value.name != "") ? contact.value.name : "no name"),
							checkbox : {
								id : contact.id,
								checked : contact.useYn
							}
						};
						list.data.push(data);
					}
				}
				list.data = selectionSort(list.data, "line1");
			} else {
				segmentObj.initContactInfo(true);
			}
			this.popupButtonLeftHandler = function(homeId, sgmtId) {
				var cloudHomeScreen = chs,
					segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
					checkboxInfo = cloudHomeScreen.getEventHandler().getSearchList().getCheckboxInfo();
				
				if (checkboxInfo && (checkboxInfo.length > 0)) {
					segmentObj.updateOption(checkboxInfo);
					
					var option = segmentObj.getOption();
					if (jQuery("#" + homeId + " #" + homeId + sgmtId).length == 0) {
						cloudHomeScreen.getSegmentManager().setSegmentObject(homeId, sgmtId, segmentObj);
						cloudHomeScreen.getSegmentManager().addSegment(sgmtId, option);
					} else {
						// update segment
						cloudHomeScreen.segmentManager.updateSegment(segmentObj);
					}
				}
				
				var hash = "editHome",
					actionParams = segmentObj;
				cloudHomeScreen.setHash(hash, actionParams);
			};
			buttons = [{
				value : "Done",
				href : "chs.segmentManager.popupButtonLeftHandler('" + homeId + "', '" + sgmtId + "')"
			}, {
				value : "Cancel",
				href : "chs.setHash('editHome')"
			}];
		} else if (type == "shortcuts") {
			placeholder = "Search Applications";
			var appInfo = segmentObj.getAppInfo(),
				appInfoLoaded = segmentObj.appInfoLoaded;
			if (appInfoLoaded) {
				list = {
					left : "icon",
					middle : 1,
					right : "checkbox",
					data : [],
					checkbox : {
						required : false,
						removable : false
					}
				};
				for (var appId in appInfo) {
					if (appInfo.hasOwnProperty(appId)) {
						var app = appInfo[appId];
						var data = {
							icon : app.value.icon,
							line1 : app.value.title,
							checkbox : {
								id : appId,
								checked : app.useYn
							}
						};
						list.data.push(data);
					}
				}
				list.data = selectionSort(list.data, "line1");
			} else {
				segmentObj.initAppInfo(true);
			}
			this.popupButtonLeftHandler = function(homeId, sgmtId) {
				var cloudHomeScreen = chs,
					segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
					checkboxInfo = cloudHomeScreen.getEventHandler().getSearchList().getCheckboxInfo();
				
				if (checkboxInfo && (checkboxInfo.length > 0)) {
					segmentObj.updateOption(checkboxInfo);
					
					var option = segmentObj.getOption();
					if (jQuery("#" + homeId + " #" + homeId + sgmtId).length == 0) {
						cloudHomeScreen.getSegmentManager().setSegmentObject(homeId, sgmtId, segmentObj);
						cloudHomeScreen.getSegmentManager().addSegment(sgmtId, option);
					} else {
						// update segment
						cloudHomeScreen.segmentManager.updateSegment(segmentObj);
					}
				}
				
				var hash = "editHome",
					actionParams = segmentObj;
				cloudHomeScreen.setHash(hash, actionParams);
			};
			buttons = [{
				value : "Done",
				href : "chs.segmentManager.popupButtonLeftHandler('" + homeId + "', '" + sgmtId + "')"
			}, {
				value : "Cancel",
				href : "chs.setHash('editHome')"
			}];
		} else if ((type == "weather") || (type == "stock")) {
			if (type == "weather") {
				placeholder = "Enter city name";
			} else {
				placeholder = "Enter company name";
			}
			this.popupButtonLeftHandler = function(homeId, sgmtId) {
				var cloudHomeScreen = chs,
					segmentObj = cloudHomeScreen.getSegmentManager().getSegmentObject(homeId, sgmtId),
					searchList = cloudHomeScreen.getEventHandler().getSearchList(),
					keyword = searchList.getSearchKeyword();
				
				if (keyword && (keyword != "")) {
					var checkboxInfo = searchList.getCheckboxInfo();
					if (checkboxInfo && (checkboxInfo.length > 0)) {
						segmentObj.updateOption(checkboxInfo);
					}
				}
				
				var hash = "editDetail",
					actionParams = cloudHomeScreen.getSegmentManager().getPopupInfo(type, { segmentObj : segmentObj });
				cloudHomeScreen.setHash(hash, actionParams);
			};
			this.popupButtonRightHandler = function(homeId, sgmtId) {
				var cloudHomeScreen = chs,
					segmentManager = cloudHomeScreen.getSegmentManager(),
					segmentObj = segmentManager.getSegmentObject(homeId, sgmtId),
					hash = "editDetail",
					actionParams = segmentManager.getPopupInfo(type, { segmentObj : segmentObj });
				cloudHomeScreen.setHash(hash, actionParams);
			};
			buttons = [{
				value : "Done",
				href : "chs.segmentManager.popupButtonLeftHandler('" + homeId + "', '" + sgmtId + "')"
			}, {
				value : "Cancel",
				href : "chs.segmentManager.popupButtonRightHandler('" + homeId + "', '" + sgmtId + "')"
			}];
			
			return { placeholder : placeholder, list : list, buttons : buttons, caller : segmentObj };
		}
		
		return { placeholder : placeholder, list : list, buttons : buttons };
	},
	
	/**
	 * sgmtId���대떦�섎뒗 segment object瑜��앹꽦, 媛�졇�⑤떎.
	 * @function
	 * @param sgmtId
	 * @returns
	 */
	getNewSegmentObject : function(sgmtId) {
		var obj = null;
		var fncName = this.getSegmentType(sgmtId);
		if (fncName == "topstory") {
			obj = new TopstorySegment(this.cloudHomeScreen);
		} else if (fncName == "snsfeeds") {
			obj = new SnsSegment(this.cloudHomeScreen);
		} else if (fncName == "daily") {
			obj = new DailyInfoSegment(this.cloudHomeScreen);
		} else if (fncName == "news") {
			obj = new NewsSegment(this.cloudHomeScreen);
		} else if (fncName == "weather") {
			obj = new WeatherSegment(this.cloudHomeScreen);
		} else if (fncName == "stock") {
			obj = new StockSegment(this.cloudHomeScreen);
		} else if (fncName == "shortcuts") {
			obj = new ShortcutSegment(this.cloudHomeScreen);
		} else if (fncName == "contacts") {
			obj = new ContactSegment(this.cloudHomeScreen);
		} else if (fncName == "gallery") {
			obj = new GallerySegment(this.cloudHomeScreen);
		} else if (fncName == "media") {
			obj = new MediaGuideSegment(this.cloudHomeScreen);
		} else if (fncName == "socialDeals") {
			obj = new SocialDealSegment(this.cloudHomeScreen);
		} else if (fncName == "ad") {
			obj = new AdvertisementSegment(this.cloudHomeScreen);
		} else if (fncName == "webclip") {
			obj = new WebclipSegment(this.cloudHomeScreen);
		} else if (fncName == "organizer") {
			obj = new OrganizerSegment(this.cloudHomeScreen);
		} else if (fncName == "samsungAd") {
			obj = new SamsungAdSegment(this.cloudHomeScreen);
		} else if (fncName == "userDefined") {
			obj = new UserDefinedSegment(this.cloudHomeScreen);
		}

		return obj;
	},
	
	/**
	 * segmentObj瑜���옣�쒕떎.
	 * @param homeId
	 * @param sgmtId
	 * @param segmentObj
	 */
	setSegmentObject : function(homeId, sgmtId, segmentObj) {
		if (this.homeInfo[homeId]) {
			this.homeInfo[homeId].objList[sgmtId] = segmentObj;
		}
	},
	
	/**
	 * homeId���대떦�섎뒗 home���랁븳 segment 以�sgmtId���대떦�섎뒗 segment��object瑜�媛�졇�⑤떎.
	 * @param homeId
	 * @param sgmtId
	 * @returns
	 */
	getSegmentObject : function(homeId, sgmtId) {
		if (this.homeInfo[homeId].objList[sgmtId]) {
			return this.homeInfo[homeId].objList[sgmtId];
		} else {
			var segmentObj = this.getNewSegmentObject(sgmtId);
			segmentObj.setHomeId(homeId);
			segmentObj.setSegmentId(sgmtId);
			return segmentObj;
		}
	},
	
	/**
	 * homeInfo��蹂�꼍��segmentObj瑜���옣�쒕떎.
	 * @param homeId
	 * @param sgmtId
	 * @param option
	 */
	updateSegmentObject : function(homeId, sgmtId, option) {
		var segmentObj = null;
		if (this.homeInfo[homeId]) {
			segmentObj = this.getSegmentObject(homeId, sgmtId);
			segmentObj.setOption(option);
		}
		
		this.setSegmentObject(homeId, sgmtId, segmentObj);
	},
	
	getSegmentManagerInfo : function() {
		var segmentManagerInfo = [];
		for (var homeId in this.homeInfo) {
			if (this.homeInfo.hasOwnProperty(homeId)) {
				var homeInfo = this.homeInfo[homeId];
				for (var sgmtId in homeInfo.option) {
					if (homeInfo.option.hasOwnProperty(sgmtId)) {
						var options = homeInfo.option[sgmtId];
						segmentManagerInfo.push({ homeId : homeId, sgmtId : sgmtId, options : options });
					}
				}
			}
		}
		
		return segmentManagerInfo;
	},
	
	startRearrangeSegments : function() {
		chs.homeEventHandler.showStatusBar("CHS loading is almost finished.");
		var segmentManager = this,
			homeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId(),
			layout = this.getCurrentHomeLayout();
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			var sgmtId = layout[i];
			jQuery("#" + homeId + ".segment_container > ul").append(jQuery("li#" + homeId + sgmtId));
		}
		var removeCount = jQuery("#" + homeId + ".segment_container > ul > li[id^=" + homeId + "]").size() - layout.length;
		if (removeCount > 0) {
//			jQuery("li[id^=" + homeId + "]:lt(" + removeCount + ")").remove();
			jQuery("li[id^=" + homeId + "]:lt(" + removeCount + ")").each(function() {
				var sgmtId = jQuery(this).attr("id").replace(homeId, "");
				segmentManager.deleteSegmentInfo(homeId, sgmtId);
				jQuery(this).remove();
			});
		}
		
		chs.homeEventHandler.hideStatusBar();
	},
	
	startSegmentEditDetail : function(homeId, sgmtId, popupType) {
		var cloudHomeScreen = chs,
			segmentObj = this.getSegmentObject(homeId, sgmtId);
		segmentObj.saveCurrentOption();
		var hash = "editDetail",
			actionParams = this.getPopupInfo(popupType, { segmentObj : segmentObj });
		cloudHomeScreen.setHash(hash, actionParams);
	}
};

/**
 * @constructor
 * @param cloudHomeScreen
 * @namespace WebclipManager
 * @memberOf CloudHomeScreen
 */
var WebclipManager = function(cloudHomeScreen) {
	this.cloudHomeScreen = cloudHomeScreen;
	this.initialize();
};

WebclipManager.prototype = {
	/**
	 * @function
	 */
	initialize : function() {
		this.webclipLoaded = false;
		
		delete this.webclipList;
		delete this.option;
		delete this.objList;
		
		this.webclipList = [];
		this.option = {};
		this.objList = {};
	},

	/**
	 * @function
	 * @param list
	 */
	setWebclipList : function(list) {
		this.webclipList = list;
	},

	/**
	 * @function
	 * @param info
	 */
	setOption : function(info) {
		var webclipId = info["webclip_id"];
		
		if (webclipId && (webclipId != "")) {
			this.webclipList.push(webclipId);
			this.option[webclipId] = {
				url : decodeURIComponent(info["url"]),
				startX : info["startx"],
				startY : info["starty"],
				endX : info["endx"],
				endY : info["endy"]
			};
		}
	},

	/**
	 * @function
	 * @param flag
	 */
	setWebclipLoaded : function(flag) {
		this.webclipLoaded = flag;
	},

	/**
	 * @function
	 * @returns {Array}
	 */
	getWebclipList : function() {
		return this.webclipList;
	},

	/**
	 * @function
	 * @returns {Array}
	 */
	getOption : function(webclipId) {
		return this.option[webclipId];
	},

	/**
	 * @function
	 * @returns
	 */
	getWebclipLoaded : function() {
		return this.webclipLoaded;
	},

	/**
	 * @function
	 */
	loadWebclips : function() {
		this.configWebclipContainer();

		var homeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId();
		for (var i=0, webclipCount=this.webclipList.length ; i<webclipCount ; ++i) {
			var webclipId = this.webclipList[i];
			
			if (webclipId) {
				var option = this.getOption(webclipId);

				this.loadWebclip(webclipId, option, true);
			}
		}
		
		// hide delete buttons
		jQuery(".icon-delete").hide();
	},

	/**
	 * @function
	 * @param webclipId
	 * @param option
	 * @param flag
	 */
	loadWebclip : function(webclipId, option, flag) {
		var webclipObj = new WebclipSegment(this.cloudHomeScreen);
		webclipObj.load("webclip", webclipId, option, flag);
		
		// save object
		this.objList[webclipId] = webclipObj;
	},
	
	getWebclipObject : function(webclipId) {
		return this.objList[webclipId];
	},
	
	setWebclipCheckbox : function() {
		var homeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId();
		for (var i=0, webclipCount=this.webclipList.length ; i<webclipCount ; ++i) {
			var webclipId = this.webclipList[i];
			
			if (webclipId && (webclipId != "")) {
				// check if this webclip is included as a home segment
				if (jQuery("#" + homeId + " #" + homeId + webclipId).length != 0) {
					jQuery("#webclip" + " #" + webclipId + " input[type=checkbox]").attr({ checked : "checked", disabled : "disabled"});
				} else {
					jQuery("#webclip" + " #" + webclipId + " input[type=checkbox]").removeAttr("checked").removeAttr("disabled");
				}
			}
		}
	},

	/**
	 * @function
	 */
	configWebclipContainer : function() {
		var cloudHomeScreen = this.cloudHomeScreen;
		var sortableSelector = "#webclip > .screen > ul";
		
		jQuery(sortableSelector).sortable();
		jQuery(sortableSelector).sortable("option", {
			"grid" : [10000, 1],
			"cursor" : "crosshair",
			"opacity" : 0.6,
			"scroll" : true,
			"z-index" : 12,
//			"revert" : true,
			"tolerance" : "pointer",
			"axis" : "y"
		});
		/*if (chsConstants.isCloudPhone) {
			jQuery(sortableSelector).sortable("option", "delay", 2000);
		}*/
		jQuery(sortableSelector).sortable({
			// stop sorting and DOM position is changed.
			update : function(event, ui) {
				cloudHomeScreen.getEventHandler().onWebclipOrderChanged();
			}
		});
		
		for (var i=0, webclipCount=this.webclipList.length ; i<webclipCount ; ++i) {
			var webclipId = this.webclipList[i];
			
			if (webclipId && (webclipId != "")) {
				this.createWebclip(webclipId);
			}
		}

		jQuery(sortableSelector).sortable("option", "disabled", true);
	},

	/**
	 * @function
	 * @param webclipId
	 */
	createWebclip : function(webclipId) {
		if (jQuery("#webclip #" + webclipId).size() == 0) {
			var innerHTML = "<li id=\"" + webclipId + "\">" +
								"<div class=\"segment\">" +
									"<h2>" + webclipId + "</h2>" +
									"<section id=\"" + webclipId + "Section\" class=\"webclip\">" +
										"<div class=\"screen\">" +
											"<iframe class=\"webclip_ifrm\" width=\"100%\" frameborder=\"0\" scrolling=\"no\" seamless=\"seamless\" noresize=\"noresize\" src=\"\"></iframe>" +
											"<div class=\"checkbox\">" +
												"<input type=\"checkbox\" webclip-id=\"" + webclipId + "\">" +
											"</div>" +
											"<a class=\"item_cover\"></a>" +
										"</div>" +
										"<div class=\"icon-delete\"></div>" +
									"</section><!-- webclip -->" +
									"<div class=\"segment_cover\"></div>" +
								"</div>" +
							"</li>";
			jQuery("#webclip > .screen > ul").append(innerHTML);
			
			jQuery("#webclip #" + webclipId + " .webclip .icon-delete").css("cursor", "pointer").unbind("click").bind("click", {
				webclipManager : this,
				webclipId : webclipId
			}, this.cloudHomeScreen.getEventHandler().onWebclipDeleted);
		}
	},

	/**
	 * @function
	 */
	startWebclipEditMode : function() {
		// enable webclip container sortable
		jQuery("#webclip > .screen > ul").sortable("option", "disabled", false);

		// add edit class into elements that have segment class
		jQuery("#webclip .segment").addClass("edit");
		
		// show delete buttons
		jQuery("#webclip .segment .icon-delete").show();
		
		// hide checkbox
		jQuery("#webclip .checkbox").hide();
		
		// change the width of screen class
		var pageWidth = window.innerWidth;
		jQuery("section .screen").css("width", pageWidth-40 + "px");
		
		// execute additional action repectively
		var layout = this.webclipList;
		for (var i=0, webclipCount=layout.length ; i<webclipCount ; ++i) {
			var webclipId = layout[i];
			
			if (webclipId && (webclipId != "")) {
				var webclipObj = this.getWebclipObject(webclipId);
				if (webclipObj && webclipObj.startEditMode) {
					webclipObj.startEditMode();
				}
			}
		}
	},

	/**
	 * @function
	 */
	finishWebclipEditMode : function() {
		// disable webclip container sortable
		jQuery("#webclip > .screen > ul").sortable("option", "disabled", true);

		// remove edit class from elements that have segment class
		jQuery("#webclip .segment").removeClass("edit");
		
		// hide delete buttons
		jQuery("#webclip .segment .icon-delete").hide();
		
		// show checkbox
		jQuery("#webclip .checkbox").show();
		
		// update webclip information
		this.updateWebclipOrder(true);
		
		// change the width of screen class
		var pageWidth = window.innerWidth;
		jQuery("section .screen").css("width", pageWidth + "px");
		
		// execute additional action repectively
//		var layout = this.cloudHomeScreen.getSegmentManager().getLayout(this.currentHomeId);
//		for (var i=0 ; i<layout.length ; ++i) {
//			var segmentObj = this.cloudHomeScreen.getSegmentManager().getSegmentObject(this.currentHomeId, layout[i]);
//			if (segmentObj.finishEditMode) {
//				segmentObj.finishEditMode();
//			}
//		}
	},

	addWebclipsToCurrentHome : function(flag) {
		var newlyChecked = jQuery("#webclip input[type=checkbox]:checked").not(":disabled"),
			newlyCheckedCount = newlyChecked.size();
		
		if (newlyCheckedCount > 0) {
			var webclipManager = this,
				cloudHomeScreen = this.cloudHomeScreen,
				homeEventHandler = cloudHomeScreen.getEventHandler(),
				segmentManager = cloudHomeScreen.getSegmentManager(),
				homeManager = cloudHomeScreen.getHomeManager(),
				homeId = homeManager.getCurrentHomeId();
			
			homeEventHandler.showStatusBar("Add Webclips To Current Home...");
			if (flag) {
				for (var i=0 ; i<newlyCheckedCount ; ++i) {
					var checkbox = newlyChecked.get(i),
						webclipId = jQuery(checkbox).attr("webclip-id"),
						option = this.getOption(webclipId);
					
					segmentManager.addSegment(webclipId, option);
					jQuery(checkbox).attr("disabled", "disabled");
				}
				
				cloudHomeScreen.updateLayout(homeId, true);
				cloudHomeScreen.showToast("Checked Webclips are added to current Home.");
			}
			homeEventHandler.hideStatusBar();
		}
	},
	
	/**
	 * @function
	 * @param webclipId
	 */
	deleteWebclip : function(webclipId) {
		var webclipManager = this,
			cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.homeEventHandler;
		
		this.saveCurrentWebclipOrder();
		
		jQuery("#webclip #" + webclipId).fadeOut("fast", function() {
			jQuery(this).remove();
			
			// delete webclip item from current home
			var homeId = cloudHomeScreen.getHomeManager().getCurrentHomeId();
			cloudHomeScreen.getSegmentManager().deleteSegment(homeId, webclipId);

			// delete webclip
			if (homeEventHandler.checkOnLine()) {
				homeEventHandler.showStatusBar("Delete Webclip...");
				if (chsConstants.isCloudPhone) {
					var valueObject = new SyncManager.WebClip();
					valueObject._webclip_id = webclipId;
					cloudHomeScreen.getSyncManager().remove(valueObject, function() {
						homeEventHandler.hideStatusBar();
					}, function(message) {
						homeEventHandler.showErrorMessage(message);
						homeEventHandler.hideStatusBar();
					}, false);
				} else {
					var url = "/aphone/chs/webclip/delete",
						type = "POST",
						params = "webclipId=" + encodeURIComponent(webclipId);
					
					if (chsConstants.workerExist) {
						var data = { url : url, type : type, data : params };
						homeEventHandler.executeWorker("deleteWebclip", data, function(xhr) {
							webclipManager.deleteWebclipCallback(xhr);
						});
					} else {
						jQuery.ajax({
							url : url,
							type : type,
							data : params,
							complete : function(xhr) {
								if (xhr.readyState == 4) {
									webclipManager.deleteWebclipCallback(xhr);
								}
							}
						});
					}
				}

				// update webclip order
				webclipManager.updateWebclipOrder();
			}
		});

		this.deleteWebclipInfo(webclipId);
	},
	
	deleteWebclipCallback : function(xhr) {
		var homeEventHandler = this.cloudHomeScreen.getEventHandler();
		
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
					// success message
					console.log("WEBCLIP DELETE SUCCESS");
					homeEventHandler.hideStatusBar();
				} else {
					// error message
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
		}
	},

	/**
	 * @function
	 * @param webclipId
	 */
	deleteWebclipInfo : function(webclipId) {
		for (var i=0, webclipCount=this.webclipList.length ; i<webclipCount ; ++i) {
			if (this.webclipList[i] == webclipId) {
				this.webclipList.splice(i, 1);
				delete this.option[webclipId];
				delete this.objList[webclipId];
				break;
			}
		}
	},

	/**
	 * @function
	 */
	updateWebclipOrder : function(pushFlag) {
		var webclipList = jQuery("#webclip > .screen > ul").sortable("toArray");

		var previousWebclipOrder = this.getPreviousWebclipOrder();
		if (previousWebclipOrder != webclipList.toString()) {
			this.setWebclipList(webclipList);
			this.updateWebclip(pushFlag);
		}
	},

	/**
	 * @function
	 */
	updateWebclip : function(pushFlag) {
		var webclipManager = this,
			cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.getEventHandler();
		
		if (homeEventHandler.checkOnLine()) {
			homeEventHandler.showStatusBar("Update Webclip...");
			if (chsConstants.isCloudPhone) {
				var valueObject = new SyncManager.WebClip();
				for (var i=0, webclipCount=this.webclipList.length ; i<webclipCount ; ++i) {
					var webclipId = this.webclipList[i],
						option = this.option[webclipId];
					
					if (webclipId && (webclipId != "") && option) {
						valueObject._sort_order = i;
						valueObject._webclip_id = webclipId;
						valueObject._url = option.url;
						valueObject._startx = option.startX;
						valueObject._starty = option.startY;
						valueObject._endx = option.endX;
						valueObject._endy = option.endY;

						cloudHomeScreen.getSyncManager().update(valueObject, function() {
							homeEventHandler.hideStatusBar();
						}, function(message) {
							homeEventHandler.showErrorMessage(message);
							homeEventHandler.hideStatusBar();
						}, false);//濡쒖뺄 �붾퉬���곸슜
					}
				}
			} else {
				var url = "/aphone/chs/webclip/update",
					type = "POST",
					params = "list=" + encodeURIComponent(this.webclipList.toString());
				
				if (pushFlag) {
					params += "&push=true";
				}
				
				if (chsConstants.workerExist) {
					var data = { url : url, type : type, data : params };
					homeEventHandler.executeWorker("updateWebclip", data, function(xhr) {
						webclipManager.updateWebclipCallback(xhr);
					});
				} else {
					jQuery.ajax({
						url : url,
						type : type,
						data : params,
						complete : function(xhr) {
							if (xhr.readyState == 4) {
								webclipManager.updateWebclipCallback(xhr);
							}
						}
					});
				}
			}
			
			// set local storage
			var webclipManagerInfo = this.getWebclipManagerInfo();
			homeEventHandler.setLocalStorage("webclipManagerInfo", JSON.stringify(webclipManagerInfo));
		} else {
			console.error("can't update webclip. (offline)");
		}
	},
	
	updateWebclipCallback : function(xhr) {
		var homeEventHandler = this.cloudHomeScreen.getEventHandler();
		
		if (xhr.status == 200) {
			var result = checkAjaxResponse(xhr.responseText);
			if (nvl(result) != "") {
				var response = JSON.parse(result);
				if (response.message.code == 0) {
					// success message
					console.log("WEBCLIP UPDATE SUCCESS");
					homeEventHandler.hideStatusBar();
				} else {
					// error message
					homeEventHandler.showErrorMessage(response.message.text);
					homeEventHandler.hideStatusBar();
				}
			}
		}
	},
	
	saveCurrentWebclipOrder : function() {
		this.previousWebclipOrder = this.webclipList.toString();
	},
	
	getPreviousWebclipOrder : function() {
		return this.previousWebclipOrder;
	},
	
	getWebclipManagerInfo : function() {
		var webclipManagerInfo = [];
		for (var webclipId in this.option) {
			if (this.option.hasOwnProperty(webclipId)) {
				var webclipInfo = this.getOption(webclipId);
				var data = { "webclip_id" : webclipId };
				for (var key in webclipInfo) {
					if (webclipInfo.hasOwnProperty(key)) {
						data[key.toLowerCase()] = webclipInfo[key];
					}
				}
				webclipManagerInfo.push(data);
			}
		}
		
		return webclipManagerInfo;
	}
};

/**
 * @constructor
 * @param cloudHomeScreen
 * @namespace CHSEventHandler
 * @memberOf CloudHomeScreen
 */
var CHSEventHandler = function(cloudHomeScreen) {
	this.cloudHomeScreen = cloudHomeScreen;
	this.tableCreatedCount = 0;
	this.syncedCount = 0;
	this.dataLoadedCount = 0;
	
	this.initialize();
};

CHSEventHandler.prototype = {
	initialize : function() {
//		window.history.replaceState(null, null, location.href.split("#")[0] + "#home");
		
		this.currentMode = "home";
		this.otherHomeLoaded = false;
		
		delete this.iscrollList;
		delete this.iscrollInfo;
		delete iscrollInterval;
		delete this.segmentScroll;
		delete this.intervalIds;
		if (this.worker) {
			this.worker.terminate();
			delete this.worker;
		}
		delete this.workerInfo;
		
		this.iscrollList = {};
		this.iscrollInfo = {};
		this.iscrollInterval = {};
		this.segmentScroll = {};
		this.intervalIds = {};
		
		if (chsConstants.workerExist) {
			this.worker = new Worker("/aphone/js/ajaxworker.js");
		}
		this.workerInfo = {};
	},
	
	/**
	 * @function
	 */
	onTableCreated : function() {
		var cloudHomeScreen = this.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.getEventHandler(),
			syncManager = this.cloudHomeScreen.getSyncManager();
		
		addCacheUpdatedHandler();
		if (syncManager) {
			pu.startMilestone("synchronize, SyncManager");
			syncManager.server_sync(function() {
				pu.finishMilestone("synchronize, SyncManager");
				homeEventHandler.showStatusBar("Synchronization end.");
				cloudHomeScreen.getData();
			}, function() {
				pu.finishMilestone("synchronize, SyncManager");
				homeEventHandler.showErrorMessage("Sync with server Error.");
				homeEventHandler.hideStatusBar();
			});
			homeEventHandler.showStatusBar("Synchronizing...");
		} else {
			this.showErrorMessage("SyncManager is not created.");
		}
	},

	/**
	 * @function
	 */
	onDataLoaded : function(tableName) {
		console.warn("[" + this.loadType + "][" + chsConstants.dataSourceCount + "-" + (++this.dataLoadedCount) + "] onDataLoaded --- : " + tableName);
		
		var cloudHomeScreen = this.cloudHomeScreen,
			homeManager = cloudHomeScreen.getHomeManager(),
			segmentManager = cloudHomeScreen.getSegmentManager();
		
		if (tableName == "chs_layout") {
			cloudHomeScreen.loadHome();
			
			// If segment option information is already loaded, then start loading segments
			/*if (this.segmentOptionInfoLoaded) {
				console.warn("CHS_SEGMENT_OPTION information is loaded in advance. Now set segment option information.");
				var optionInfo = segmentManager.optionInfo;
				if (optionInfo.length == 0) {
					optionInfo = segmentManager.getInitSegmentOptions(cloudHomeScreen.homeManager.getCurrentHomeId());
				}
				segmentManager.setSegmentOptions(optionInfo);
				segmentManager.loadSegments(cloudHomeScreen.homeManager.getCurrentHomeId());
				
				// set local storage
				var segmentManagerInfo = segmentManager.getSegmentManagerInfo();
				this.setLocalStorage("segmentManagerInfo", JSON.stringify(segmentManagerInfo));
			}*/
		}
		
		if (this.dataLoadedCount == chsConstants.dataSourceCount) {
			var homeId = homeManager.getCurrentHomeId();
			
			this.dataLoadedCount = 0;
//			this.layoutInfoLoaded = this.segmentOptionInfoLoaded = false;
			
			segmentManager.loadUnloadedSegments(homeId);
			
			if (this.checkOnLine() && (this.loadType != "cache")) {
				segmentManager.removeUnusedSegments(homeId);
				pu.report();
			}
		}
	},
	
	/**
	 * @function
	 */
	onDBDataChanged : function() {
		var homeEventHandler = this;

		this.dataReloadedCount = 0;
		if (chsConstants.isCloudPhone) {
			if (jQuery("#" + this.cloudHomeScreen.getHomeManager().getCurrentHomeId() + " > ul").sortable("toArray").toString() != "[object Object]") {
				homeEventHandler.cloudHomeScreen.getDataFromLocalStorage();
				homeEventHandler.cloudHomeScreen.getData(true);
			}
		}
	},
	
	// TODO : deprecated
	onDataReloaded : function(tableName) {
		console.warn("onDataReloaded --- : " + tableName);
		if (tableName == "chs_layout") {
			this.initialize();
			this.cloudHomeScreen.refreshHome();
		}
		if (++this.dataReloadedCount == 3) {
			this.dataReloadedCount = 0;
			this.layoutInfoLoaded = this.segmentOptionInfoLoaded = false;
//			this.cloudHomeScreen.getSegmentManager().loadSegments(this.cloudHomeScreen.getHomeManager().getCurrentHomeId());
			this.cloudHomeScreen.getSegmentManager().loadUnloadedSegments(this.cloudHomeScreen.getHomeManager().getCurrentHomeId());
		}
	},

	checkEditHomeCondition : function() {
		if (this.checkOnLine()) {
			var hash = "editHome";
			this.cloudHomeScreen.setHash(hash);
		} else {
			this.cloudHomeScreen.showToast("You can't edit Cloud Home Screen now. The network is disconneced.");
		}
	},
	
	/**
	 * @function
	 */
	onSegmentOrderChanged : function(homeId) {
		var segmentManager = this.cloudHomeScreen.getSegmentManager();
		
		segmentManager.saveCurrentHomeLayout();		// save current home's layout
		segmentManager.updateLayout(homeId, true);		// update DB
	},

	/**
	 * @function
	 */
	onWebclipOrderChanged : function() {
		var webclipManager = this.cloudHomeScreen.getWebclipManager();
		
		webclipManager.saveCurrentWebclipOrder();
		webclipManager.updateWebclipOrder();
	},

	/**
	 * @function
	 * @param event
	 */
	onSegmentDeleted : function(event) {
		if (isMyEvent(event) && isLeftButtonClick(event)) {
			var segmentManager = event.data.segmentManager,
				homeId = event.data.homeId,
				sgmtId = event.data.sgmtId;

			segmentManager.deleteSegment(homeId, sgmtId);
		}
	},
	
	/**
	 * 
	 * @param event
	 */
	onSegmentItemDeleted : function(segmentObj, optionId) {
		jQuery(segmentObj.mainSelector + " #" + optionId).fadeOut("fast", function() {
			jQuery(this).remove();
			segmentObj.deleteOptions([optionId]);
		});
	},

	/**
	 * @function
	 * @param event
	 */
	onWebclipDeleted : function(event) {
		if (isMyEvent(event) && isLeftButtonClick(event)) {
			var webclipManager = event.data.webclipManager,
				webclipId = event.data.webclipId;

			webclipManager.deleteWebclip(webclipId);
		}
	},
	
	// TODO : deprecated
	inCaseOfNoContents : function(sgmtId) {
		var homeId = this.cloudHomeScreen.getHomeManager().getCurrentHomeId();
		var sgmtName = this.cloudHomeScreen.getSegmentManager().getSegmentName(sgmtId);
		
		// delete segment
		this.cloudHomeScreen.getSegmentManager().deleteSegment(homeId, sgmtId);
		
		// show toast
		this.cloudHomeScreen.showToast(sgmtName + " segment has just been deleted because of having no contents.");
	},

	/**
	 * @function
	 * @param mode
	 */
	setCurrentMode : function(mode) {
		this.currentMode = mode;
	},

	/**
	 * @function
	 * @returns
	 */
	getCurrentMode : function() {
		return this.currentMode;
	},

	/**
	 * @function
	 * @param flag
	 */
	setOtherHomeLoaded : function(flag) {
		this.otherHomeLoaded = flag;
	},
	
	/**
	 * @function
	 * @returns
	 */
	getOtherHomeLoaded : function() {
		return this.otherHomeLoaded;
	},
	
	onPageResize : function(event) {
		var cloudHomeScreen = (event ? event.data.cloudHomeScreen : this.cloudHomeScreen),
			homeEventHandler = cloudHomeScreen.getEventHandler(),
			currentMode = homeEventHandler.getCurrentMode();
		
		homeEventHandler.refreshScreenWidth();		// change the width of screen class
		
		if (currentMode.toLowerCase().indexOf("webclip") != -1) {
			jQuery("#homeWrapper").css("visibility", "hidden").show();
		}
		
		homeEventHandler.refreshMovingAreaWidth();
		homeEventHandler.refreshHomeHeight();		// change the height of #wrap
		homeEventHandler.resetSegmentIScroll();		// reset segment iscroll
		
		if (currentMode.toLowerCase().indexOf("webclip") != -1) {
			jQuery("#homeWrapper").css("visibility", "visible").hide();
		}
	},
	
	onOrientationChange : function(event) {
		var cloudHomeScreen = event.data.cloudHomeScreen;
		
		cloudHomeScreen.homeEventHandler.onPageResize(event);
	},
	
	refreshScreenWidth : function(selector) {
		var pageWidth = window.innerWidth;
		
		if ((selector == null) || (selector == undefined)) {
			selector = "";
		} else {
			selector += " ";
		}
		
		jQuery("#wrap").css("max-width", pageWidth + "px");
		jQuery(".screen").css("width", pageWidth + "px");
		jQuery(".webclip_ifrm").css("width", pageWidth + "px");
		if (this.currentMode.indexOf("edit") != -1) {
			jQuery(selector + "section .screen").css("width", pageWidth-40 + "px");
			jQuery(selector + ".webclip_ifrm").css("width", pageWidth-40 + "px");
		}
		
		if (this.currentMode.indexOf("multiple") != -1) {
			if (pageWidth < 640 || pageWidth > 1024) {
				jQuery(".home_container.change .screen").css("width", 480);
			} else {
				jQuery(".home_container.change .screen").css("width", 720);
			}
			
			jQuery(".segment_container > ul").each(function() {
				var containerHeight = jQuery(this).outerHeight(true);
				var style = "-webkit-transform:scale(0.7,0.7) translate(" + -(pageWidth*0.15) + "px, " + -(containerHeight*0.15/0.7) + "px);" +
							"-moz-transform:scale(0.7,0.7) translate(" + -(pageWidth*0.15) + "px, " + -(containerHeight*0.15/0.7) + "px);" +
							"-o-transform:scale(0.7,0.7) translate(" + -(pageWidth*0.15) + "px, " + -(containerHeight*0.15/0.7) + "px);" +
							"-ms-transform:scale(0.7,0.7) translate(" + -(pageWidth*0.15) + "px, " + -(containerHeight*0.15/0.7) + "px);";
				jQuery(this).attr("style", style);
			});
		}
	},
	
	refreshMovingAreaWidth : function() {
		var homeManager = this.cloudHomeScreen.getHomeManager(),
			segmentManager = this.cloudHomeScreen.getSegmentManager(),
			homeId = homeManager.getCurrentHomeId(),
			layout = segmentManager.getLayout(homeId);
		
		for (var i=0, segmentCount=layout.length ; i<segmentCount ; ++i) {
			var sgmtId = layout[i],
				segmentObj = segmentManager.getSegmentObject(homeId, sgmtId);
			
			if (segmentObj && segmentObj.setMovingAreaWidth) {
				segmentObj.setMovingAreaWidth(((this.currentMode.indexOf("edit") != -1) ? true : false));
			}
		}
		
		if (this.currentMode.indexOf("multiple") != -1) {
			homeManager.changeHomeAreaWidth();
		}
	},
	
	refreshHomeHeight : function() {
		var pageHeight = window.innerHeight,
			searchListHeaderHeight = jQuery(".search_container .ui-search").outerHeight(true),
			searchListFooterHeight = jQuery(".search_container footer").outerHeight(true);
		
		jQuery(".ui-pop").css("height", pageHeight);
		
		// Change the height of search container ul
		jQuery(".search_container").css("height", pageHeight + "px");
		jQuery("#searchList_iscroll").css("height", pageHeight - searchListHeaderHeight - searchListFooterHeight);
		this.setVerticalIScroll("searchList_iscroll", true);
	},
	
	/** PopupList, SearchList, Toast */
	setPopup : function(popup) {
		this.popup = popup;
	},
	
	getPopup : function() {
		return this.popup;
	},
	
	setSearchList : function(searchList) {
		this.searchList = searchList;
	},
	
	getSearchList : function() {
		return this.searchList;
	},
	
	setToast : function(toast) {
		this.toast = toast;
	},
	
	getToast : function() {
		return this.toast;
	},
	
	/** error message */
	showErrorMessage : function(message) {
		console.error(message);
		this.cloudHomeScreen.showToast(message);
	},
	
	showAjaxError : function(position, error) {
		var message =	"Position : " + position +
						"\nstatus : " + error.status + 
						"\nresponseText : " + error.responseText +
						"\nstatusText : " + error.statusText;
		this.showErrorMessage(message);
	},
	
	/** segment sortable related function */
	segmentDragHandler : function(event, target) {
		if (event.type == "taphold") {
//			jQuery("#log").append("<p>taphold!!</p>");
//			jQuery("#log").append("<p>In Mobile Browser</p>");
			jQuery(target).attr("style", "background-color:#000;opacity:0.5;");		// mark taphold condition
			this.isTaphold = true;		// Set taphold condition true
			this.mousedownEventActivated = false;
			this.segmentMove = false;
		} else if (event.type == "touchmove") {
//			jQuery("#log").append("<p>touchmove!!</p>");
			this.segmentMove = true;
			if (this.isTaphold) {
//				jQuery("#log").append("<p>after taphold.</p>");
				if (!this.mousedownEventActivated) {
					this.mousedownEventActivated = true;
					this.activateMouseEvent(target, event.originalEvent.touches[0], "mousedown");
					event.preventDefault();		// prevent browser scroll
				} else {
//					jQuery("#log").append("<p>touchmove event</p>");
				}
				this.activateMouseEvent(target, event.originalEvent.touches[0], "mousemove");
				this.lastTouchmoveEvent = event.originalEvent.touches[0];
			}
		} else if ((event.type == "touchend") || (event.type == "touchcancel")) {
			if (event.currentTarget === event.originalEvent.currentTarget) {
//				jQuery("#log").append("<p>touchend!!</p>");
				if (this.isTaphold) {
					this.isTaphold = false;		// Set taphold condition false
					this.activateMouseEvent(target, this.lastTouchmoveEvent, "mouseup");
//					event.preventDefault();
					jQuery(target).removeAttr("style");
				}
				// if tap event, then start segment edit detail mode
				if (!this.segmentMove) {
					return true;
				}
				this.segmentMove = false;
			}
		}
	},
	
	activateMouseEvent : function(target, touch, type) {
//		jQuery("#log").append("<p>in activateMouseEvent function.");
//		jQuery("#log").append("<p>target : " + target.id + ", touch : " + touch + ", type : " + type + "</p>");
//		jQuery("#log").append("<p>clientX/Y:(" + touch.clientX + "," + touch.clientY + "), screenX/Y:(" + touch.screenX + "," + touch.screenY + ")</p>");
		
		if ((touch == null) || (touch == undefined)) {
			touch = { screenX : 0, screenY : 0, clientX : 0, clientY : 0};
		}
		
		var mouseEvent = document.createEvent("MouseEvent");
//		jQuery("#log").append(" create mouse event :" + mouseEvent);
		mouseEvent.initMouseEvent(type, true, true, window, 1, (touch.screenX?touch.screenX:0), (touch.screenY?touch.screenY:0), (touch.clientX?touch.clientX:0), (touch.clientY?touch.clientY:0), false, false, false, false, 0/* left */, null);
//		jQuery("#log").append(" init mouse event.");
		target.dispatchEvent(mouseEvent);
//		jQuery("#log").append(" dispatch event.</p>");
	},
	
	/**
	 * MediaGuide��SNSFeeds���숈쁺��踰꾪듉���대┃�덉쓣 ���몄텧�쒕떎.
	 * @param event
	 */
	onVideoPlayButtonClick : function(source) {
		var cloudHomeScreen = this.cloudHomeScreen,
			width = window.innerWidth,
			height = window.innerHeight;
		
		jQuery(".video_player").fadeIn(function() {
			var frameWidth = jQuery(".video_player .pop-fg").outerWidth(true),
				frameHeight = jQuery(".video_player .pop-fg").outerHeight(true);
			
			jQuery(".video_player .pop-fg").css({
				top : (chsConstants.isCloudPhone ? 140 : parseInt(height/2) - parseInt(frameHeight/2)),
				left : "16.7%"
			});
			
			jQuery(".video_player .close").unbind("click").bind("click", cloudHomeScreen.homeEventHandler.onVideoCloseButtonClick);
			jQuery(".video_player .pop-fg iframe").remove();
			jQuery(".video_player .pop-fg").append("<iframe src=\"" + source + "\" width=\"100%\" height=\"100%\" frameborder=\"0\">");
		});
	},
	
	onVideoCloseButtonClick : function(event) {
		jQuery(".video_player iframe").remove();
		jQuery(".video_player").fadeOut();
	},
	
	openLink : function(url) {
		return window.open(url, "", "");
	},
	
	/** iScroll related functions */
	hasIScroll : function(id) {
		if (this.iscrollList[id]) {
			return true;
		}
		
		return false;
	},
	
	createIScroll : function(id, options, buttons) {
		var homeEventHandler = this;
		this.setIScroll(id, new iScroll(id, options));
		this.setIScrollOnBeforeEvent(id);
		this.setIScrollOptions(id, {
			"onScrollMove" : function() {
				if (homeEventHandler.segmentScroll[id]) {
					homeEventHandler.segmentScroll[id].isMove = true;
				}
			},
			"onScrollEnd" : function() {
				if (homeEventHandler.segmentScroll[id]) {
					homeEventHandler.segmentScroll[id].isMove = false;
				}
			}
		});
		
		if (buttons) {
			this.setIScrollHorizontalButtons(id, buttons);
			
			jQuery(buttons.prev).attr("href", "javascript:chs.homeEventHandler.scrollToPage('" + id + "', 'prev', 0, 500);");
			jQuery(buttons.next).attr("href", "javascript:chs.homeEventHandler.scrollToPage('" + id + "', 'next', 0, 500);");
			
			this.setIScrollOptions(id, {
				"onScrollMove" : function() {
					if (homeEventHandler.iscrollInterval[id]) {
						homeEventHandler.iscrollInterval[id].count = 0;
					}
					
					if (homeEventHandler.segmentScroll[id]) {
						homeEventHandler.segmentScroll[id].isMove = true;
					}
				},
				"onScrollEnd" : function() {
					homeEventHandler.setIScrollHorizontalButtons(id, buttons);
					if (homeEventHandler.iscrollInterval[id]) {
						homeEventHandler.iscrollInterval[id].isMove = false;
					}
					
					if (homeEventHandler.segmentScroll[id]) {
						homeEventHandler.segmentScroll[id].isMove = false;
					}
				}
			});
		}
	},
	
	setIScrollOnBeforeEvent : function(id) {
		var homeEventHandler = this;
		var iscroll = this.getIScroll(id);
		var direction = ((iscroll.options.hScroll) ? "h" : "v");
		
		var options = {
				"onBeforeScrollStart" : function(event) {
					var windowEvent = window.event;
					var anyEvent = (chsConstants.isMobile ? windowEvent.touches[0] : windowEvent);
					
					homeEventHandler.iscrollInfo[id] = { firstEvent : windowEvent, startPos : { x : anyEvent.pageX, y : anyEvent.pageY } };
					homeEventHandler.segmentScroll[id] = { isMove : false };
					
					if (direction == "v") {
						if (event.target.nodeName.toLowerCase() != "input") {
							event.preventDefault();		// prevent browser scroll
						}
					} else {
						homeEventHandler.iscrollInterval[id] = { isMove : true, count : 0, id : setInterval(function() {
							if (homeEventHandler.iscrollInterval[id] && (!homeEventHandler.iscrollInterval[id].isMove || (homeEventHandler.iscrollInterval[id].count > 500))) {
								if (homeEventHandler.iscrollInterval[id].count > 500) {
									homeEventHandler.scrollToCurrentPage(id, 250);
								}
								clearInterval(homeEventHandler.iscrollInterval[id].id);
								clearInterval(homeEventHandler.iscrollInterval[id].timeId);
								delete homeEventHandler.iscrollInterval[id];
							}
						}, 1) };
						homeEventHandler.iscrollInterval[id].timeId = setInterval(function() {
							if (homeEventHandler.iscrollInterval[id]) {
								homeEventHandler.iscrollInterval[id].count += 1;
							}
						}, 1);
					}
				},
				"onBeforeScrollMove" : function(event) {
					if (homeEventHandler.iscrollInfo[id]) {
						var windowEvent = window.event;
						var anyEvent = (chsConstants.isMobile ? windowEvent.touches[0] : windowEvent);
						
						var xDiff = Math.abs(homeEventHandler.iscrollInfo[id].startPos.x - anyEvent.pageX);
						var yDiff = Math.abs(homeEventHandler.iscrollInfo[id].startPos.y - anyEvent.pageY);
						if (((direction == "h") && (xDiff < yDiff)) || ((direction == "v") && (xDiff > yDiff))) {
							iscroll._end(homeEventHandler.iscrollInfo[id].firstEvent);
							if (direction == "h") {
								homeEventHandler.iscrollInterval[id].isMove = false;
								
								if (homeEventHandler.segmentScroll[id]) {
									homeEventHandler.segmentScroll[id].isMove = true;
								}
							}
						} else if (xDiff == yDiff) {
							if (homeEventHandler.segmentScroll[id]) {
								homeEventHandler.segmentScroll[id].isMove = true;
							}
						} else {
							if (direction == "h") {
								event.preventDefault();		// prevent browser scroll
							}
						}
						
						delete homeEventHandler.iscrollInfo[id];
					}
				}
		};
		this.setIScrollOptions(id, options);
	},
	
	setIScrollHorizontalButtons : function(id, buttons) {
		var iscroll = this.getIScroll(id);
		
		(iscroll.currPageX == 0) ? jQuery(buttons.prev).fadeOut() : jQuery(buttons.prev).fadeIn();
		(iscroll.currPageX+1 == iscroll.pagesX.length) ? jQuery(buttons.next).fadeOut() : jQuery(buttons.next).fadeIn();
	},
	
	setIScrollOptions : function(id, options) {
		if (this.iscrollList[id]) {
			for (var key in options) {
				if (options.hasOwnProperty(key)) {
					this.iscrollList[id].options[key] = options[key];
				}
			}
		}
	},
	
	setIScroll : function(id, iscroll) {
		this.iscrollList[id] = iscroll;
	},
	
	getIScroll : function(id) {
		return this.iscrollList[id];
	},
	
	getIScrollList : function() {
		return this.iscrollList;
	},
	
	removeIScroll : function(id) {
		if (this.iscrollList[id]) {
			delete this.iscrollList[id];
		}
	},
	
	refreshIScroll : function(id) {
		if (this.iscrollList[id]) {
			this.iscrollList[id].refresh();
		}
	},
	
	resizeIScroll : function(id) {
		if (this.iscrollList[id]) {
			this.iscrollList[id]._resize();
		}
	},
	
	scrollTo : function(id, xPos, yPos, time) {
		if (this.iscrollList[id]) {
			this.iscrollList[id].scrollTo(xPos, yPos, time);
		}
	},
	
	scrollToPage : function(id, pageX, pageY, time) {
		if (this.iscrollList[id]) {
			this.iscrollList[id].scrollToPage(pageX, pageY, time);
		}
	},
	
	scrollToCurrentPage : function(id, time) {
		if (this.iscrollList[id]) {
			var currPageX = this.iscrollList[id].currPageX;
			var currPageY = this.iscrollList[id].currPageY;
			this.scrollToPage(id, currPageX, currPageY, time);
		}
	},
	
	disableIScroll : function(id) {
		if (this.iscrollList[id]) {
			this.iscrollList[id].disable();
		}
	},
	
	enableIScroll : function(id) {
		if (this.iscrollList[id]) {
			this.iscrollList[id].enable();
		}
	},
	
	unbindIScroll : function(id, eventList) {
		if (this.iscrollList[id]) {
			var event = eventList.split(" ");
			for (var i=0, count=event.length ; i<count ; ++i) {
				this.iscrollList[id]._unbind(event[i]);
			}
		}
	},
	
	setVerticalIScroll : function(id, noMove) {
		if (this.hasIScroll(id)) {
			this.refreshIScroll(id);
			if (!noMove) {
				this.scrollToPage(id, 0, 0, 0);
			}
		} else {
			var options = { hScroll : false, vScroll : true, hScrollbar : false, vScrollbar : true, hideScrollbar : true, fadeScrollbar : true, desktopCompatibility : true };
			this.createIScroll(id, options);
		}
	},
	
	resetSegmentIScroll : function() {
		var homeList = this.cloudHomeScreen.getHomeManager().getHomeList();
		for (var i=0, homeCount=homeList.length ; i<homeCount ; ++i) {
			var layout = this.cloudHomeScreen.getSegmentManager().getLayout(homeList[i].id);
			for (var j=0, segmentCount=layout.length ; j<segmentCount ; ++j) {
				var id = homeList[i].id + layout[j] + "Section";
				if (this.hasIScroll(id)) {
					var iscroll = this.getIScroll(id);
					
					var xPos = iscroll.pagesX[iscroll.currPageX];
					var maxScrollX = iscroll.maxScrollX;
					
					this.refreshIScroll(id);
					this.scrollTo(id, ((xPos > maxScrollX) ? xPos : maxScrollX), 0, 0);
				}
			}
		}
	},
	
	killAllSegmentIScroll : function(id, evet) {
		for (var iid in this.iscrollList) {
			if (this.iscrollList.hasOwnProperty(iid)) {
				if (iid != id) {
					var iscroll = this.getIScroll(iid);
					iscroll._end(event);
					iscroll.disable();
				}
			}
		}
	},
	
	restoreAllSegmentIScroll : function(event) {
		for (var iid in this.iscrollList) {
			if (this.iscrollList.hasOwnProperty(iid)) {
				var iscroll = this.getIScroll(iid);
				iscroll._end(event);
				iscroll.enable();
			}
		}
	},
	
	/** localStorage related functions */
	setLocalStorage : function(key, value) {
		try {
			if (this.checkOnLine()) {
				localStorage.setItem(key, value);
			}
		}
		catch (e) {
			console.warn(e.message);
			jQuery("#log").append("localStorage.setItem(), " + e.message);
		}
	},
	
	getLocalStorage : function(key) {
		var value = "";
		try {
			value = localStorage.getItem(key);
		}
		catch (e) {
			console.warn(e.message);
			jQuery("#log").append("<span>localStorage.getItem(), " + e.message + "</span>");
		}
		
		return value;
	},
	
	removeLocalStorage : function(key) {
		try {
			localStorage.removeItem(key);
		} catch (e) {
			console.warn(e.message);
		}
	},
	
	clearLocalStorage : function() {
		try {
			localStorage.clear();
		} catch (e) {
			console.warn(e.message);
		}
	},
	
	/** setInterval, clearInterval function */
	setInterval : function(id, action, period, params) {
		this.clearInterval(id);
		this.intervalIds[id] = setInterval(function() {
			action(params);
		}, period);
	},
	
	clearInterval : function(id) {
		if (this.intervalIds[id]) {
			clearInterval(this.intervalIds[id]);
			delete this.intervalIds[id];
		}
	},
	
	onUnload : function(event) {
		var cloudHomeScreen = event.data.cloudHomeScreen,
			homeEventHandler = cloudHomeScreen.homeEventHandler;
		
		for (var id in homeEventHandler.intervalIds) {
			if (homeEventHandler.intervalIds.hasOwnProperty(id)) {
				homeEventHandler.clearInterval(id);
			}
		}
		
		if (homeEventHandler.worker) {
			homeEventHandler.worker.terminate();
		}
	},
	
	increaseSegmentLoadCount : function() {
		var layout = this.cloudHomeScreen.getSegmentManager().getCurrentHomeLayout();
		if (++this.segmentLoadCount == layout.length) {
			this.cloudHomeScreen.getSegmentManager().startRearrangeSegments();
		}
	},
	
	showStatusBar : function(message) {
		statusbar.show(message);
	},
	
	hideStatusBar : function() {
		statusbar.hide();
	},
	
	executeWorker : function(id, ajaxData, callback) {
		var homeEventHandler = this;
		
		this.workerInfo[id] = { callback : callback };
		this.worker.onmessage = function(event) {
			var data = event.data,
				workerId = data.id;
			
			if (homeEventHandler.workerInfo.hasOwnProperty(workerId)) {
				homeEventHandler.workerInfo[workerId].callback(data);
//				homeEventHandler.destroyWorker(workerId);
			}
		};
		
		ajaxData.id = id;
		this.worker.postMessage(ajaxData);
	},
	
	destroyWorker : function(id) {
		if (this.workerInfo.hasOwnProperty(id)) {
			delete this.workerInfo[id];
		}
	},
	
	checkOnLine : function() {
		if (navigator.onLine) {		// FIX_NAVI
			return true;
		} else {
			console.warn("[navigator.onLine : " + navigator.onLine + "] Network is currently disconnected.");
//			return false;
			return true;
		}
	},
	
	changeHomeWrapperStatus : function() {
		var hash = location.hash;
		
		
		if (!this.homeWrapperStatusChanged && ((hash.indexOf("addSegment") != -1) || (hash.indexOf("editDetail") != -1) || (hash.indexOf("optionSearch") != -1))) {
			/**  */
			var scrollTop = jQuery(document.body).scrollTop();
			jQuery("#homeWrapper").css("height", window.innerHeight).scrollTop(scrollTop);
			this.homeWrapperStatusChanged = true;
		} else if (this.homeWrapperStatusChanged && (hash.indexOf("editHome") != -1)) {
			/**  */
			var scrollTop = jQuery("#homeWrapper").scrollTop();
			jQuery("#homeWrapper").removeAttr("style");
			jQuery(document.body).scrollTop(scrollTop);
			this.homeWrapperStatusChanged = false;
		}
	}
};